Mygel Bergstresser Mygel Bergstresser - 5 months ago 19
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.


<ul id="main-li">


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


According to David Wash:

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

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


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 ( && === "LI") {
        let elements = document.getElementById('main-li').children;
        for (let i = 0; i < elements.length; ++i) {
}, 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.