Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Remove a class on the button which was previously clicked using vanilla JavaScript

Hi all, I'm stuck with a problem. I'm adding active classes to the pagination button which is clicked. NOW I want to remove the active class on the button which was previously clicked.

Any ideas?

    for(let i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", () => {
            showPage((i + 1),students);
            console.log(`page number ${i + 1} is clicked`);
            buttons[i].firstElementChild.setAttribute('class', 'active');
        });
    };

1 Answer

You can use another eventListener that takes and if statement to check if the Element being called upon already has that class. If it does you use button[i].firstElementChild.classList.remove("active"). You could also just modify your existing code to include that if statement.