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!');
  });
Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 12 days ago.

Related Topics

Related Articles

About the author

Stefan standing in the park in front of a green background

Frontend nerd with over ten years of experience, "Today I Learned" blogger, conference speaker, Tiny helpers maintainer, and DevRel at Checkly.