.empty() vs .remove() vs .detach() – jQuery

Do you know that jQuery provides various methods to remove elements from DOM? These methods are .empty(), .remove() and .detach(). And in this post, I will show you how these methods (.empty vs .remove vs .detach) are different from each other.

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

.remove(): This method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

I had already posted about .empty() vs .remove(). So please read the below post first, before going further.

Okay, so got the difference between .empty() and .remove(). So now you might be wondering what is .detach()?

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

Let see the differences with an example. I have created a div element with some text and assigned hover event to this element. This hover event basically add/remove CSS class to the div.

//Code Starts
$("#dvjQuery").hover(function() {
    $(this).addClass('highlight');
}, function() {
   $(this).removeClass('highlight');
});
//Code Ends

Now, remove the div element using jQuery and add it again in the page.

//Code Starts
var dvjQuery = null;
dvjQuery = $("#dvjQuery").remove();
$("#dvParent").html(dvjQuery);
//Code Ends

See result below.

First, take mouse of div and see that hover event is working. Then remove the div and add it again. And you will find that hover event is not working.

Okay, now let's do the same thing but this time using .detach() method.

//Code Starts
var dvjQuery = null;
dvjQuery = $("#dvjQuery").detach();
$("#dvParent").html(dvjQuery);
//Code Ends

See result below.

Again, take mouse of div and see that hover event is working. Then detach the div and attach it again. And you will find that hover event is working.

So to summarize, there are 3 differences between .remove() and .detach()

  • remove() method would erase data associated with the element(data that had been set using the data() method).
  • remove() method would also erase the event associated with the element.
  • If you are not concerned about the data and event then use remove() as it is faster than detach(). There is a performance test created at jsPerf.com for remove() and detach() and below is the result.

Check out this test yourself here

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...