Home > Blockchain >  DOM. Why the class won't remove after I click on again
DOM. Why the class won't remove after I click on again

Time:03-27

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 >Lorem ipsum dolor sit.</li>
  <li >Lorem ipsum dolor sit.</li>
  <li >Lorem ipsum dolor sit.</li>
  <li >Lorem ipsum dolor sit.</li>
</ul>

CodePudding user response:

  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>

CodePudding user response:

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 >Lorem ipsum dolor sit.</li>
  <li >Lorem ipsum dolor sit.</li>
  <li >Lorem ipsum dolor sit.</li>
  <li >Lorem ipsum dolor sit.</li>
</ul>

  • Related