What's the difference between empty()
and remove()
methods in jQuery
, and when we call any of these methods, the objects being created will be destroyed and memory released?
Asked
Active
Viewed 5.6k times
103

informatik01
- 16,038
- 10
- 74
- 104

mabuzer
- 6,497
- 6
- 35
- 41
3 Answers
164
empty()
will empty the selection of its contents, but preserve the selection itself.remove()
will empty the selection of its contents and remove the selection itself.
Consider:
<div>
<p><strong>foo</strong></p>
</div>
$('p').empty(); // --> "<div><p></p></div>"
// whereas,
$('p').remove(); // --> "<div></div>"
Both of them remove the DOM objects and should release the memory they take up, yes.
Here are links to documentation, which also contains examples:
-
1What about event handlers? I have a weird case where empty+append twice, with different appends causes the second set of appended items to execute the handlers of the first set. – Killroy Jan 08 '15 at 19:15
-
1@way too late, but they also remove the handler as well. there is a chance that you had those handlers registered with a function like `live` or `delegate`. – undone Dec 20 '17 at 11:24
56
The documentation explains it very well. It also contains examples:
before:
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
.remove():
$('.hello').remove();
after:
<div class="container">
<div class="goodbye">Goodbye</div>
</div>
before:
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
.empty():
$('.hello').empty();
after:
<div class="container">
<div class="hello"></div>
<div class="goodbye">Goodbye</div>
</div>
As far as memory is concerned, once an element is removed from the DOM and there are no more references to it the garbage collector will reclaim the memory when it runs.

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
empty will not touch the attributes of the selector. If you want to remove the attributes of the selector element, I noticed that the jQuery removeAttr and removeClass are buggy in firefox. So the option I had was to use the remove method and add the container element again then append child nodes to the same. – randominstanceOfLivingThing Dec 12 '13 at 17:56
-
Perfect summary, this explains it so well! For me even better than the accepted answer. – JonSnow Jan 30 '19 at 14:52
2
$("body").empty()
-- it' removes the HTML DOM elements inside the body tag -
when you declare $("body").remove()
- it remove the entire HTML DOM along with body TAG .

SheetJS
- 22,470
- 12
- 65
- 75

user1452840
- 221
- 1
- 4
- 9
-
17What does this answer provide that is missing in the existing answers that have been here for three years? – jcsanyi Aug 03 '13 at 06:06