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? FI, 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.
As 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.