Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all JavaScript event listeners of an element and its children? [duplicate]

Tags:

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.

like image 833
Tower Avatar asked Jul 11 '10 09:07

Tower


People also ask

Which mode allows you to remove all event listeners from an element?

removeEventListener() The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget. addEventListener() from the target.

Does removing an element remove event listeners?

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.

Is there a way to remove all event listeners?

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.

Should you always remove event listeners?

TLDR; Always remove event listeners when you don't plan on using them any longer.


1 Answers

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.

like image 138
25 revs, 4 users 83% Avatar answered Oct 09 '22 10:10

25 revs, 4 users 83%