Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are event listeners in jQuery removed automatically when you remove the element using .html()?

In jQuery if we use .remove() for removing some element, then all bound events and jQuery data associated with the elements are removed.

But what happens if we "remove" the elements with .html()?

Do we need to unbind all the elements prior to change any html for avoiding memory leaks?

like image 746
Enrique Avatar asked Sep 25 '11 23:09

Enrique


People also ask

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.

Does jQuery empty Remove event handlers?

This answer contradicts the documentation: api.jquery.com/empty "To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

Can you remove event listeners?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.

How do you remove all event listeners from an element?

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.


2 Answers

Yes, they will be removed. jQuery will clean up events etc related to the removed elements. It will NOT copy events if you do something like $(elm1).html($elm2.html())

like image 94
kinghfb Avatar answered Oct 09 '22 08:10

kinghfb


Yeah, they will be removed even when you use html(). The jQuery source code confirms it.

like image 34
Anurag Avatar answered Oct 09 '22 09:10

Anurag