Add and remove classes when click on multiple div using javascript

I am actually trying to add class (Selected) to the label when clicked and remove Class from neighbour label.

Issue is it doesn’t work when there is 2 div, the below code only work on the 1st Div or when i click on the label of the second label, first label active gets removed

const menuLis = document.querySelectorAll(".top-nav > label");

for (let label of menuLis) {
  
  label.addEventListener("click", function(){
    // 1. Remove Class from All Lis
    for (let label of menuLis) {
      label.classList.remove('selected');
    }
    
    // 2. Add Class to Relevant Li
    this.classList.add('selected');
  });
  
}
.selected{color:red}
<div class="grid-item">
  <section>
    <div class='top-nav'>
      <label>Coffee</label>
      <label>Tea</label>
      <label>Milk</label>
    </div>
  </section>
</div>
<br><br>
<div class="grid-item">
  <section>
    <div class='top-nav'>
      <label>Coffee</label>
      <label>Tea</label>
      <label>Milk</label>
    </div>
  </section>
</div>

Thanks

>Solution :

You’re removing the class from all the items in menuLis. You should get a list of just the labels in the current .top-nav section and remove the class from them.

const menuLis = document.querySelectorAll(".top-nav > label");

for (let label of menuLis) {
  
  label.addEventListener("click", function(){
    let container = this.closest('.top-nav');
    let curMenuLis = container.querySelectorAll("label");
    // 1. Remove Class from All Lis
    for (let label of curMenuLis) {
      label.classList.remove('selected');
    }
    
    // 2. Add Class to Relevant Li
    this.classList.add('selected');
  });
  
}
.selected{color:red}
<div class="grid-item">
  <section>
    <div class='top-nav'>
      <label>Coffee</label>
      <label>Tea</label>
      <label>Milk</label>
    </div>
  </section>
</div>
<br><br>
<div class="grid-item">
  <section>
    <div class='top-nav'>
      <label>Coffee</label>
      <label>Tea</label>
      <label>Milk</label>
    </div>
  </section>
</div>

Leave a Reply