toggle active class on click

15 Views Asked by At

I want to toggle the 'active' class on a list of elements (filters) when one of them is clicked, but I'm seeking a more concise way to do it without using two nested loops.

This is what I tried it works fine but I feel nesting a loop inside it's parent loop feels wrong to me

JS



filters.forEach(elem => {

  elem.addEventListener('click', () => {

    

    filters.forEach(item => item.classList.remove('active'));

    item.classList.add('active');

  })

})


HTML



<div class="filters">

        <button id="all" class="active">All</button>

        <button id="active">Active</button>

        <button id="completed">Completed</button>

      </div>
0

There are 0 best solutions below