Basically I’m trying to optimize my jQuery code by unbinding elements anytime is necessary, or that I need to re-bind them, but I have a question, does “destroying” an element also destroys the event attached to that element?
$(element).bind("click", function(){...});
$(element).parent().html("");
Also I’m not sure if this is done with the .html(“”), do I have to use a .remove() to do the trick?
As long as you use jQuery methods to add/remove elements and bind events, all should be fine. When you bind an event to an element (or use something like
.data()), jQuery stores this information in a place called$.cache. When you use jQuery methods to manipulate the DOM, jQuery takes care of cleaning up these things – because there really is no actual connection between the elements and$.cache. So if you added a div to the page, bound aclickevent to it with jQuery, then removed it withnode.parentNode.removeChild(node);,$.cacheis not cleaned up. If you would like evidence, look in the jQuery source for the methods likehtml,remove,replaceWithand similar ones, and you’ll find calls like this:This effectively cleans up the
$.cacheso that everything is taken care of. The point is that if you use the library for (everything) you do, you shouldn’t have to worry about these things.Using
htmlis tricky though – be careful what you pass to it. If you want to pass it a new DOM structure, likeUsing something like
$("#container").html(div);will not actually bind that click event handler. Using something like.appendwill though. Just wanted to point that out. (this is unrelated to destroying/removing elements)