So, I know that when I execute .remove() on an element in the DOM, it and all its children are removed and flagged for deletion/garbage collection. Similarly, all elements’ jQuery UI widgets will fire their “destroy” methods and all entries in the .data() space will be deleted for each element. In deciding to clean out a portion of my DOM tree, what I need to know is does remove also actually trigger .off() for each element explicitly, or do I need to do that myself?
For instance, say I have the series of divs as so:
<div id="A-1">
<div class="HasEventListener DelegatedEventBindPoint id="B-1">
<button class="CreatesDelegatedEvent" id="C-1" />
</div>
<button class="HasEventListener NonDelegatedEvent" id="B-2" />
</div>
So if I execute $(“#A-1”).remove(), does this effectively invoke commands similar to $(“.HasEventListener”).off()?
Yes, it unbinds all event handlers.
Source.
You can use
detach()if you want to keep the event handlers.Also, you mention…
That isn’t necessarily true. You may still have references to those elements. Instead, the reference count will be decremented, and if it reaches 0, then it may be flagged for GC.
jsFiddle.