Adding class on click and removing this class from all elements on the array

Hi guys. The problem I am currently facing is shown in this fiddle

What I want to do is to add pin–active class to the clicked element and delete it from all the other elements.

I’m struggling with adding a classList.remove function. Do not know how to choose the elements with pin–active class.

I do not require a full solution, just some hints or articles with similar problem. Have been researching for few days now but apparently I suck at googling.

1 method:
remove a given class from all the elements before adding it

     e => e.classList.remove('pin--active')

2 method:
remember which element is currently active, and deactivate it when other element clicked

var pin = document.querySelectorAll('.pin');

var active;

for (var i = 0; i < pin.length; i++) {
  pin[i].addEventListener('click', function (evt) {
  if (active) { active.classList.remove('pin--active') }


  active = evt.currentTarget     

1 Like

Thank you very much, Marzelin! Appreciate your help!

Hi Marzelin,

I will probably need your help again.

I am trying to do the same thing using delegation.

The only thing I can’t wrap my head around - the button does not get the required class when I click on a number. How can I avoid that?

That’s an interesting case.
The simplest way would be to check also the parent node of a target.

var pin = Array.from(document.querySelectorAll('.pin'));
var theParent = document.querySelector('.menu');

theParent.addEventListener('click', function (event) {
	var target =;
  if (pin.includes(target)) {
      pin.forEach( e => e.classList.remove('pin--active'));

  if (pin.includes(target.parentNode)) {
      pin.forEach( e => e.classList.remove('pin--active'));

}, true);