views:

618

answers:

2

I'm using JQuery to set the HTML inside a div. Something like this:

$(div).html(strHtmlBlob);

strHtmlBlob is a chunk of HTML returned via Ajax from the server. After, it's assigned, I set up some events for elements in the new HTML blob by doing this:

$(div).find("a").click(a_ClickHandler);

That all works perfectly fine. The problem is REMOVING the events. I want to make sure I clean up the DOM properly.

I'm removing the HTML like so:

$(div).html("");

But I can see that the events are still there. Is there a way to clean up events for elements that no longer exist?

+2  A: 
$(div).find('a').unbind('click');

Check out the documentation.

Alternatively, you should empty() it:

$(div).empty();

According to the docs:

Note that this function starting with 1.2.2 will also remove all event handlers and internally cached data.

Paolo Bergantino
+4  A: 

Use .remove() instead of .html("")

That will clear the elements and events all at once. JQuery does a lot of cleanup magic under the covers if you let it.

Er, why did you delete the contents of this answer?
Brian Campbell