Published at
Updated at
Reading time
1min

Removing event listeners from DOM elements is pretty annoying because you must have the registered event handler function at hand.

function handleEvent() { /* ... */ }

// add an event listener
document.querySelector('button')
  .addEventListener('click', handleEvent);

// to remove an event listener, the event type ('click') 
// and the function ('handleEvent') have to match 
// the `addEventListener` call
document.querySelector('button')
  .removeEventListener('click', handleEvent);

With somewhat modern JavaScript, you could also use AbortSignals or the once config option to remove event listeners, but what if it isn't your source code that's adding event listeners? What if there's one annoying 3rd party script messing with your events and you have to keep it?

Today I learned about a nuclear option to remove all existing event listeners.

const button = document.querySelector('button);

// replace the element with a copy of itself
// and nuke all the event listeners
button.replaceWith(button.cloneNode(true));

Boom! And that's it โ€” replacing a DOM element with a cloned version of itself removes all previously registered event handlers. Pretty handy!

Event handlers defined in an on* HTML attribute will be preserved when you clone a DOM element.

<!-- This event handler will be copied when you cloned the node -->
<button onclick="console.log('Still here!')"`>click me</button>

If you want to see this pattern in action, here we go. ๐Ÿ‘‡

// Attach multiple event listeners
// to the same button
const button = document.getElementById('cta-btn')

for(let i = 0; i < 3; i++) {
  button.addEventListener('click', () => {
    alert(`${i + 1}. event listener of 3...`);
  });
}

document.getElementById('nuke-btn')
  .addEventListener('click', (event) => {
    // Boom! Nuke and remove
    // all registered event listeners
    button.replaceWith(button.cloneNode(true));

    alert('All existing event listeners cleared!');
  });
If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles