JavaScript – How can I toggle between 2 classes by clicking on the same element on JS.

I need your help in some work,

When I click on an element on an HTML page I try to toggle between classes but unfortunately once toggled I can’t change it back.

Tried to return query selector but failed.

This is the code I wrote.

let fetchNumbers = document.querySelectorAll(`.cardnumber`);

    for (let index = 0; index < fetchNumbers.length; index++) {
    
    if (fetchNumbers[index].classList.contains('unselected') === true) {
        fetchNumbers[index].addEventListener(`click`, function () {
            fetchNumbers[index].classList.add(`selected`);
            fetchNumbers[index].classList.remove(`unselected`);
            fetchNumbers = document.querySelectorAll(`.cardnumber`);
            return fetchNumbers;
        }); 
    } else {
        fetchNumbers[index].addEventListener(`click`, function () {
            fetchNumbers[index].classList.add(`unselected`);
            fetchNumbers[index].classList.remove(`selected`);
            fetchNumbers = document.querySelectorAll(`.cardnumber`)
            return fetchNumbers;
        }); 
    }
}

Thanks in advance

Write a Comment