0

I add elements one by one. Every time I create an element, I add click listener to class. On the second time, the first class has 2 listeners.

I try to remove click listener from created elements by class name:

var kitElementPlus = document.getElementsByClassName('kitelement-plus')
for (let i = 0; i < kitElementPlus.length; i++) {
    kitElementPlus[i].removeEventListener('click', kitElementPlusFC);
};
for (let i = 0; i < kitElementPlus.length; i++) {
    kitElementPlus[i].addEventListener('click', kitElementPlusFC);
};

I still have more than one listener on previous created elements.

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
awariat
  • 331
  • 1
  • 5
  • 22
  • 2
    What is `kitElementPlusFC`? Please provide a [mre]. – ADyson Oct 19 '21 at 12:03
  • 1
    consider [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – pilchard Oct 19 '21 at 12:04
  • You can use Event Delegation. That means, besides attaching event listener to each child element you can attach it to parent element only – Dostonbek Oripjonov Oct 19 '21 at 12:05
  • If you just want to remove all the click handlers then https://stackoverflow.com/questions/19469881/remove-all-event-listeners-of-specific-type may be of interest. But yeah, consider replacing this whole setup with delegated events to begin with, then it should be much less complicated overall. – ADyson Oct 19 '21 at 12:05
  • 1
    Why are you not adding the events to the element that is created? Seems odd to keep looping over them – epascarello Oct 19 '21 at 12:06

0 Answers0