Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Toggling class on targeted element and removing class from siblings

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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'))
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading