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?
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.
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.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
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.
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())
Yeah, they will be removed even when you use html()
. The jQuery source code confirms it.
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