views:

70

answers:

3

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?

+3  A: 

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
A: 

The empty() method will clear all child nodes from the matched elements. However those matched elements will remain in DOM. The remove() method removes the matched elements from DOM.

korchev
+2  A: 
  • Empty will remove all the contents of the selection.
  • Remove will remove the selection and its contents.

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.

nickf