Is it possible to remove all event listeners of an element and its children? Something like:
myElem.removeEventListeners();
I need this because I have a complex element with events, and I need to create a copy of it -- like a static image that does not react to any events.
removeEventListener() The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget. addEventListener() from the target.
In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.
To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.
TLDR; Always remove event listeners when you don't plan on using them any longer.
If you use cloneNode
, the event listeners won't be copied.
If you want a robust solution your best bet is probably to write a wrapper to attach/detach
listeners, and keep track of them yourself. Something like Dean Edwards' addEvent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With