How to remove all event listeners from a DOM element
- 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. ๐
Join 5.5k readers and learn something new every week with Web Weekly.