Just wondering how is this managed from the memory point of view.
Let's say I have this HTML page.
<div id="container">
<div id="someID"></div>
<div>
and the following jQuery code:
$("#someID").click(function(){
//do something
});
Now somewhere in my script I need to empty (clear) all the content in #container
:
$("#container").empty();
Does this automatically remove/unbind the click event, or do I have to do it myself?
Is this something browser specific?
Just wondering how is this managed from the memory point of view.
Let's say I have this HTML page.
<div id="container">
<div id="someID"></div>
<div>
and the following jQuery code:
$("#someID").click(function(){
//do something
});
Now somewhere in my script I need to empty (clear) all the content in #container
:
$("#container").empty();
Does this automatically remove/unbind the click event, or do I have to do it myself?
Is this something browser specific?
Share Improve this question edited Sep 22, 2019 at 13:11 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 30, 2012 at 17:52 Doua BeriDoua Beri 10.9k18 gold badges95 silver badges143 bronze badges 1- 2 This is answered directly in the jQuery documentation for empty() – jholloman Commented Jul 30, 2012 at 17:57
4 Answers
Reset to default 5Yes, the .empty()
method unbinds handlers, and clears all other data stored in jQuery.cache
for all elements nested within #container
.
jQuery only binds a single (generic) handler to an element. All other handlers and data are stored in jQuery.cache
. The data for each element is cross-referenced by a serial number that jQuery puts directly on the DOM node.
So this is a jQuery specific system. The only browser specific concern is how jQuery binds the generic handler, and jQuery takes care of that unbinding as well.
From the docs:
"To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves."
I think what you're looking for, is..
$('something').remove(); /removes element and children
$('something').empty(); // clears children
Both would remove all data
and events
associated with the removed elements.
jQuery.empty()
:
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.`
If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use
.detach()
instead.
$("#container").unbind();
// Remove a previously-attached event handler from the elements.
$('something').empty();
// Clear children.
$('something').remove();
// Removes element and children.