Code has been added to clipboard!

Understanding jQuery .detach() and How It Differs From remove()

Reading time 1 min
Published Jan 18, 2018
Updated Sep 27, 2019

jQuery detach: Main Tips

  • jQuery .detach() removes selected elements from the DOM.
  • Unlike a similar remove() method, .detach() keeps the element's jQuery data.

Understanding .detach()

jQuery .detach() method removes the selected elements. However, it keeps the events and data, so they can be inserted again at a later time.

In the example below, <div> element is removed after a click event:

Example
$("button").click(() => {
    $("div").detach();
});

The syntax for jQuery .detach() is as follows:

$(selector).detach();

All you need to specify is a selector to filter the elements to remove.

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 28/01/2021
3176 People Used
Only 97 Left
Rating
5.0