1
votes

I have these event listeners attached to an element dynamically like this:

const allTitles = document.querySelectorAll('.question-title');
allTitles.forEach(title => {
   title.addEventListener("click", (e) => {
      // some code goes here using e above
   });
});

How can we remove all attached event listeners? As we have no reference to each listener and it's function this seems a bit confusing.

4

4 Answers

1
votes

Just add the event listener to the parent element of all your objects and listen for clicks on the parent element

parentElement.addEventListener('click', (e) => {
     console.log(e.target) // this will be your title if you click on that, otherwise you can just return a falsy value
})
1
votes

Store the event listener in a variable. Then you can remove it with removeElementListener.

var listeners = [];
allTitles.forEach(title => {
   var listener = (e) => {
      // some code goes here using e above
   });
   title.addEventListener("click", listener);
   listeners.push(listener);
});

Then, you can remove a listener like this:

title.removeElementListener(listeners[0]);
0
votes

You can remove the same way you added them, but using removeEventListener. Try giving the function you used to add to them a name first, and then do something like this

allTitles.forEach(title => {
  title.removeEventListener("click", onClickFunction});
});

You can read more about it here

0
votes

Simple answer: without reference to event handler, we can't. At least not elegantly.

The only working but brute-force option is to throw away original element with attached listener and re-create it from scratch. Re-assigning outerHTML does that:

allTitles.forEach(title => {
  title.outerHTML = title.outerHTML; // nuke listeners
});