Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading