.empty() vs .remove() vs .detach()

jQuery provides various methods to remove elements from DOM. These methods are

  • .empty()
  • .remove() and
  • .detach()

.empty(): This method removes all the child element of the matched element from DOM.

.remove(): This method used when you want to remove the element itself, as well as everything inside it.
(This method takes elements out of the  DOM)

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements.
detach method is useful in the scenario of removing elements are to be reinserted/added into the DOM at a later time.

Example 1:

HTML :
<div>
<div>HELLO</div>
<div>BYE</div>
</div>

JQUERY :

$(‘.hello’).empty();
$(‘.hello’).remove();

OUTPUT DOM : empty()

<div>
<div></div>
<div>BYE</div>
</div>

OUTPUT DOM : remove()

<div>
<div>BYE</div>
</div>

Exampke 2:

var temp = null;
temp = $(“#dvjQ”).detach();
$(“#dvjQ”).html(temp);

Note : Then detach the div and attach it again  remove also do the same the difference is it also erase the event associated with the element.(hover event….)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.