patrick
patrick

Reputation: 9742

Can removing dom elements with listeners cause a memory leak?

Let's say I have this HTML:

<ul class="waka_waka">
  <li>Fozzy Bear</li>
  <li>Steve Martin</li>
  <li>John Candy</li>
</ul>

... and then an event listener is added with jQuery:

$('ul li').click(function() { console.log('waka_waka!!!'); });

If suddenly at some point one does:

$('.waka_waka').remove();

Are those event listeners automatically detached and released? Or will this actually cause a leak of memory? Is it best practice for one to remove those listeners prior to removing?

Upvotes: 3

Views: 459

Answers (1)

Jack
Jack

Reputation: 11003

According to the jQuery DOCS remove also removes all bound event handlers

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

However have a look at this question jQuery memory leak with DOM removal, it seems like there might have been a memory leak at one point (note that that question is quite old so it should have hopefully been resolved by now).

Upvotes: 2

Related Questions