16

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?

Enrique
  • 4,693
  • 5
  • 51
  • 71

3 Answers3

16

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

kinghfb
  • 1,011
  • 5
  • 14
13

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

Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 1
    Thanks Anurag, I know you was the first and you are certifying your answer (+1 for that), but kinghfb need more points, so I will mark his answer as accepted for motivating him, I hope you understand. Thanks ! – Enrique Sep 25 '11 at 23:28
  • At any rate there should be an SO badge for validating your answer with a link to the source code :) – Tobias J Sep 29 '14 at 19:25
1

Just to expand a bit:

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

bendytree
  • 13,095
  • 11
  • 75
  • 91