I want to toggle elements and I need a class names for that. How can I get a class name of the nested element in stimulus.js and change it? F.I, I need to toggle the "ul" element that is initially hidden.
div data-controller="my_controller"
a data-action="click->my_controller#toggle_my_elements"
| Click
ul.is-hidden id="my-id" data-target="my_controller.mytext"
li
| Text to be toggled.
and in stimulus controller I have:
import { Controller } from 'stimulus'
export default class extends Controller {
static targets = ["mytext"]
toggle_my_elements(){
console.log("debuggin") //Ok
const class_name = this.mytextTarget.className
}
}
I tried to call a js function className
but it seems js functions don't work in the way they used to.
I just can't figure out how to get it.
I want to toggle elements and I need a class names for that. How can I get a class name of the nested element in stimulus.js and change it? F.I, I need to toggle the "ul" element that is initially hidden.
div data-controller="my_controller"
a data-action="click->my_controller#toggle_my_elements"
| Click
ul.is-hidden id="my-id" data-target="my_controller.mytext"
li
| Text to be toggled.
and in stimulus controller I have:
import { Controller } from 'stimulus'
export default class extends Controller {
static targets = ["mytext"]
toggle_my_elements(){
console.log("debuggin") //Ok
const class_name = this.mytextTarget.className
}
}
I tried to call a js function className
but it seems js functions don't work in the way they used to.
I just can't figure out how to get it.
3 Answers
Reset to default 5As StimulusJS target is a HTML element, you can use its classList
property
this.mytextTarget.classList.remove('is-hidden')
You could do the following to get the ul
class:
static targets = [ "mytext" ]
connect() {
this.mytextClass = this.data.get("class") || "is-hidden"
}
Then use the following action descriptor to toggle your ul
element
toggle(event) {
event.preventDefault();
this.mytextTargets.forEach(target => {
target.classList.toggle(this.mytextClass)
})
}
Have you tried element[:class]
?
That's how I access the class of the html element from a Stimulus Reflex in ruby since element.class
returns the class of the element (a StimulusReflex::Element) instead of the "btn btn-primary" String I was expecting.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744295731a4567249.html
评论列表(0条)