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

100
Views
DOM. Why the class won't remove after I click on again

I tried to style some element by click on them by giving them a class. Only one that I click on will have the style. But if I click the element twice, the class won't remove. I use toggle, but still does not work

const lists = document.querySelectorAll('.list');
lists.forEach(list => {
  list.addEventListener('click', () => {

    // remove the previous class active
    lists.forEach(list => list.classList.remove("active"))
    list.classList.toggle('active');

  });
});
.list.active {
  color: crimson;
}
<ul>
  <li class="list">Lorem ipsum dolor sit.</li>
  <li class="list">Lorem ipsum dolor sit.</li>
  <li class="list">Lorem ipsum dolor sit.</li>
  <li class="list">Lorem ipsum dolor sit.</li>
</ul>

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

0

  1. your .classList.remove() doesn't specify any class to remove.
    Change to .classList.remove('active')
  2. list.classList.toggle('active'); will never toggle active class. It will be the same as list.classList.add('active');

If you really want to toggle active class do

document.querySelectorAll('#list > li').forEach( (list_el,_,all) =>
  {
  list_el.onclick =_=>
    {
    if ( list_el.classList.toggle('active') )
      all.forEach( li => li.classList.toggle('active', list_el===li ))
    }
  })
#list > li {
  cursor : pointer;
  }
.active {
  color: crimson;
  }
<ul id="list">
  <li>Lorem ipsum dolor sit.</li>
  <li>Lorem ipsum dolor sit.</li>
  <li>Lorem ipsum dolor sit.</li>
  <li>Lorem ipsum dolor sit.</li>
</ul>

about 4 years ago · Juan Pablo Isaza Report

0

lists.forEach(list => list.classList.remove("active"))

you don't need this part as toggle('active') will remove the class when you click twice

const lists = document.querySelectorAll('.list');
lists.forEach(list => {
  list.addEventListener('click', () => {

    // remove the previous class active
    
    list.classList.toggle('active');

  });
});
.list.active {
  color: crimson;
}
<ul>
  <li class="list">Lorem ipsum dolor sit.</li>
  <li class="list">Lorem ipsum dolor sit.</li>
  <li class="list">Lorem ipsum dolor sit.</li>
  <li class="list">Lorem ipsum dolor sit.</li>
</ul>

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!