1

I have the following HTML on a page:

<div class="component">
  <a href="#" class="delete">delete</a>
</div>

And I have the following script at page load:

$(document).ready(function(){

  $('a.delete').on('click', function() {
    ....
  });

});

This page has other Javascript code that manipulates the page and removes via:

$('.component').remove();

My question: do I need to remove (unbind) the event handler before removing the HTML? If not, will there be any memory leak or other impact?

Thanks and regards!

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
curious1
  • 14,155
  • 37
  • 130
  • 231

1 Answers1

3

Because you're using jQuery, you don't need to worry about it.

Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

http://api.jquery.com/remove/ (emphasis added)

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Matt, what if I insert the removed component to a new place on the same page? Should I remove the event handler before insert? I know that I have to re-attach the event handler AFTER insert if I want the click handler to continue to work. – curious1 Sep 04 '13 at 05:41
  • 1
    Please read carefully. The last sentence that I quoted addresses that. – Matt Ball Sep 04 '13 at 13:00