Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!