I’m having trouble getting a class to properly toggle on the clicked element while removing the same class from siblings. The below code works as expected except when you click an element that has the active class already. For example, when you click one of these li elements it will get the active class and the active class will also get removed from its siblings. However, if an element already has the active class, any additional clicks to that element will not remove the active class.
Javascript
const topUI = document.querySelectorAll('.top-left-icons ul li');
topUI.forEach(li => {
li.addEventListener('click', e => {
[...li.parentElement.children].forEach(sib => sib.classList.remove('active'))
li.classList.toggle('active');
})
})
HTML
<div class="top-left-icons menu">
<ul>
<li id="home">
<img src="images/home-outline.png">
</li>
<li id="information">
<img src="images/information-outline.png">
</li>
<li id="full-screen">
<img src="images/full-screen-outline.png">
</li>
<li id="air-flow">
<img src="images/air-flow-outline.png">
</li>
<li id="contact">
<img src="images/contact-outline-person.png">
</li>
</ul>
</div>
>Solution :
The forEach() loop removes the class from all the elements, including the one you clicked on. Then you toggle the element that was clicked on, which adds the class back.
You should skip the current element in the loop.
[...li.parentElement.children].forEach(sib => {
if (sib != li) {
sib.classList.remove('active'))
}
});