Enrique
Enrique

Reputation: 4833

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?

Upvotes: 16

Views: 4582

Answers (4)

Mahmoud Magdy
Mahmoud Magdy

Reputation: 923

yes, better to move elements you not need them to be lost to another display none container but use JavaScript appendChild method as it not copy element it just send the element from one container to another so you not lose event listeners this way.

ex

<div id="hidden_container" style="display:none;"></div>
<script>
  $("#hidden_container").get(0).appendChild("#elm_with_event").get(0));
</script>

Upvotes: 0

bendytree
bendytree

Reputation: 13589

Just to expand a bit:

So if you want to retain listeners, use .detach().

Upvotes: 1

kinghfb
kinghfb

Reputation: 1021

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

Upvotes: 17

Anurag
Anurag

Reputation: 141859

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

Upvotes: 13

Related Questions