javascript - How to get class of the element in stimulus.js - Stack Overflow

I want to toggle elements and I need a class names for that.How can I get a class name of the nested e

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.

Share Improve this question edited Feb 17, 2020 at 2:11 tagaism asked Jan 23, 2020 at 20:33 tagaismtagaism 6422 gold badges8 silver badges28 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744295731a4567249.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信