Black friday

Save big!

All courses under $5 - for a limited time!

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.