jQuery API

.detach()

.detach( [ selector ] ) Returns: jQuery

Description: Remove the set of matched elements from the DOM.

  • version added: 1.4.detach( [ selector ] )

    selectorA selector expression that filters the set of matched elements to be removed.

The .detach() 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.

Example:

Detach all paragraphs from the DOM

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<p>Hello</p> 
  how are 
  <p>you?</p>
  <button>Attach/detach paragraphs</button>
<script>
    $("p").click(function(){
      $(this).toggleClass("off");
    });
    var p;
    $("button").click(function(){
      if ( p ) {
        p.appendTo("body");
        p = null;
      } else {
        p = $("p").detach();
      }
    });</script>
</body>
</html>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .detach() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • kuswantin
    Any work around for jQuery 1.3.2? My CMS is still too far to deploy jQuery 1.4
  • looking for an answer as well. for now gonna try:

    $('.selector').clone(true).end().remove();
  • elem.clone(true);
    elem.remove();
  • This is indeed very very useful, thanks! Maybe an "empty()" version would be cool too, though I currently use:

    $(selector).contents().detach();

    which works too.
  • .detach() is possibly the best function added in 1.4
    This allows removing elements from the DOM without destroying them which opens up large possibilities for keeping a clean DOM structure which helps the browser stay fast.