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 https://jsfiddle.net/ayydv3jy/11/

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

  Array.from(pin).forEach(
     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') }

  console.log(evt.currentTarget)
  evt.currentTarget.classList.add('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.

https://jsfiddle.net/ayydv3jy/18/

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 = event.target;
  
  if (pin.includes(target)) {
      pin.forEach( e => e.classList.remove('pin--active'));
  	  return event.target.classList.add('pin--active');

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

}, true);