tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

detach()

detach()

Returns: jQuery

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

.detach( [ selector ] )

version added: 1.4
selector
A 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
$("p").click(function(){
      $(this).toggleClass("off");
    });
    var p;
    $("button").click(function(){
      if ( p ) {
        p.appendTo("body");
        p = null;
      } else {
        p = $("p").detach();
      }
    });
The output of the code above will be:

Full source

Detach all paragraphs from the DOM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" language="javascript">
   $(document).ready(function(){
    $("p").click(function(){
      $(this).toggleClass("off");
    });
    var p;
    $("button").click(function(){
      if ( p ) {
        p.appendTo("body");
        p = null;
      } else {
        p = $("p").detach();
      }
    });
  });
  </script>
</head>
<body>
  <p>Hello</p> 
  how are 
  <p>you?</p>
  <button>Attach/detach paragraphs</button>
</body>
</html>
Was this information helpful?
   

Comments