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?
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.