How can I select all the li child of an element in js

How can I select all the li child of an element in js

I want to select all the li elements of this item (direct child, grand child all)

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo sit aspernatur asperiores quidem illo natus dolor laborum corporis blanditiis beatae. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo sit aspernatur asperiores quidem illo natus dolor laborum corporis blanditiis beatae.

document.querySelectorAll(".stellarnav li.has-sub").forEach(item =>{
    item.addEventListener("click", function(){
        console.log(item)
        // to make you understand I described it below in css language
        // in CSS language it is like this: item li

        // then I want to removeAttribute from the all the child
        // like this
        document.querySelectorAll(`${item} li`).forEach(childItem =>{
            childItem.removeAttribute("open");
        })
        // how can I achive this thing to select all the li childs
        // here I tried it but this is not valid
    })
});```

Answer

Just run this.querySelectorAll('li').forEach(li=>li.removeAttribute("open"));

This is a document querySelectorAll document

Tested code:

document.querySelectorAll(".nav li.has-sub").forEach(item =>{
      
  item.addEventListener("click", function(){
      this.querySelectorAll('li').forEach(li=>li.removeAttribute("open"));
  })
})
li[open]{
  color: red;
}
.nav >li{
  margin: 10px
}
<ul class='nav'>
  <li class='has-sub'>
     this is has-sub li 1
    <ul>
      <li open>
        this is open
      </li>
      <li open>
        this is open
      </li>
      <li>   this is another li
      </li>
    </ul>
  </li>
  <li class='has-sub'>
     this is has-sub li 2
    <ul>
      <li open>
        this is open
      </li>
      <li open>
        this is open
      </li>
      <li> this is another li
      </li>
    </ul>
  </li>
  <li>
     this is li 3
    <ul>
      <li open>
        this is not has-sub open
      </li>
      <li open>
       this is not has-sub open
      </li>
      <li>  this is another li
      </li>
    </ul>
  </li>
</ul>

Leave a Reply

Your email address will not be published. Required fields are marked *