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:
- your
.classList.remove()
doesn't specify any class to remove.
Change to.classList.remove('active')
list.classList.toggle('active');
will never toggleactive
class. It will be the same aslist.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>