Mygel Bergstresser Mygel Bergstresser - 1 month ago 7
Javascript Question

How to add an active class on specific “li” on user click

I've scoured the web for a straightforward answer and I have not been able to find it. Spent too long trying to figure this out, but I'd appreciate any help or the right direction.

HTML

<ul id="main-li">
<li>item1</li>
<li>item1</li>
<li>item1</li>
</ul>


JavaScript:

document.getElementById('main-li').addEventListener("click", function(e) {
if (e.target && e.target.nodeName === "LI") {
e.target.classList.add("active-class");
}
});


JSFiddle
https://jsfiddle.net/kw0rr3fv/1/

According to David Wash: https://davidwalsh.name/event-delegate


Event delegation allows you to avoid adding event listeners to
specific nodes; instead, the event listener is added to one parent.
That event listener analyzes bubbled events to find a match on child
elements


What is the best way to remove the previous active-class while attaching the class to the selected element?

Answer

The only way that exists to remove a class to each child of the UL, is to iterate over them.

If you wish to avoid frameworks like jQuery, you can simply achieve it with a very short code:

document.getElementById('main-li').addEventListener("click", function(e) {
    if (e.target && e.target.nodeName === "LI") {
        let elements = document.getElementById('main-li').children;
        for (let i = 0; i < elements.length; ++i) {
            elements[i].classList.remove("active-class");
        }
        e.target.classList.add("active-class");
     }
}, true);

As you see I just added a very short loop to your code that removes the class (it won't block in case the element doesn't have the class).

In the last line of code you may notice I have added a true value: this is the use capture and is used to suggest that UL event must be captured by LI childrens.

Comments