'How to find index of previous active class

I am trying to make a slider. Most of it is working till here, but I am not getting further as I want to find the index of the item which I removed the class as last from.(before the click)

So when I click on a dot, the clicked dot must be enabled and get the active class and the class on the previous active dot needs to be removed.

navDots.addEventListener('click', e => {
         
         // make only dot's clickable
         const targetDot = e.target.closest('.dots');

        // disable NavDots for clicks
        if(!targetDot)return;
            
        //Find the index of the clicked btn
        const dotIndex = Array.from(targetDot.parentNode.children).indexOf(targetDot);
        console.log(dotIndex);

        // Add the active class tot the dot     
        navDots.children[dotIndex].classList.add('active');
       
        //HOW TO REMOVE PREVIOUS DOT ACTIVE style?
            
            //show image with dotIndex
            showImages(dotIndex);
});

Thank you for helping,

r,y.



Solution 1:[1]

The most efficient way is to store active element in a variable:

let activeElement = null;
navDots.addEventListener('click', e => {

    // make only dot's clickable
    const targetDot = e.target.closest('.dots');

    // disable NavDots for clicks
    if(!targetDot)return;

    //Find the index of the clicked btn
    const dotIndex = Array.from(targetDot.parentNode.children).indexOf(targetDot);
    console.log(dotIndex);

    // remove previous active class
    activeElement && activeElement.classList.remove("active");

    // save new active element
    activeElement = navDots.children[dotIndex];
    // Add the active class tot the dot     
    activeElement.classList.add('active');

    //HOW TO REMOVE PREVIOUS DOT ACTIVE style?

    //show image with dotIndex
    showImages(dotIndex);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vanowm