.detach() JQ Home  <<  Manipulation  <<  .detach()

DOM removal.

Description

The .detach() method is used to remove the matched set from the DOM, including any descendants.

  • The .detach() method retains all bound events and jQuery data associated with the detached elements, so they can be reinserted into the DOM at a later time if required.
  • Use the .remove() method when you want to completely remove the elements, all bound events and jQuery data associated with them.
  • Use the .empty() method when you want to completely remove all child nodes, their bound events and jQuery data associated with them.

Syntax

Signature Description
.detach( [selector] )Remove the matched set from the DOM.

Parameters

Parameter Description Type
selectorA string containing a CSS or custom jQuery selector to match elements against.Selector

Return

A jQuery object containing the detached matched set.

.detach( [selector] ) Example  Manip.  <<  Top

Remove the matched set from the DOM.

In the example below when the left button is pressed we detach or reattach all the curry images below.

When the right button is pressed we detach or reattach the 'chicken masala' image.

Tinker with the buttons and notice how the images are reattached due to the 'chicken masala' image being in the jQuery object for the left button (images), or when it has been removed first, to the second jQuery object, for the right button (images2).

a picture of curry a picture of curry a picture of curry


$(function(){
  var images = null;
  var images2 = null;
  $('#btn1').on('click', function() {
    if ( images ) {
         images.prependTo('#div4');
         images = null;
    } else {
         images = $('.curry').detach();
    }
  });
  $('#btn2').on('click', function() {
    if ( images2 ) {
    	images2.prependTo('#div4');
    	images2 = null;
    } else {
    	images2 = $('.curry').detach('#curry2');
    }
  });
});

Press the button below to action the above code:

            

Related Tutorials

jQuery Intermediate Tutorials - Lesson 5 - DOM Removal & Replacement