D. G.
D. G.

Reputation: 451

Does jquery .remove() trigger .off() on descendant DOM elements

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()?

Upvotes: 3

Views: 1607

Answers (1)

alex
alex

Reputation: 490607

Yes, it unbinds all event handlers.

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

Source.

You can use detach() if you want to keep the event handlers.

Also, you mention...

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.

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.

Upvotes: 5

Related Questions