The detach() method removes the selected elements, including all text and child nodes. However, the advantage of using this method is that it keeps data and events i.e keeps a copy of the removed elements, which allows them to be reinserted at a later time.
Program to detach an element from DOM and then reattach it.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>detach demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<p>Hello</p>
how are
<p>you?</p>
<button>Attach/detach paragraphs</button>
 
<script>
var a;
$( "button" ).click(function() {
  if ( a ) 
  {
    a.appendTo( "body" );
    a = null;
  } else 
  {
    a = $( "p" ).detach();
  }
});
</script>
 
</body>
</html>
Explanation:
The detach() method removes the selected elements "p" in this case. A variable a is declared and on the basis of that vale "p" element is detached from DOM or appended to the body. On clicking of button value of a is checked which if true then element "p" is attached to the body else it is detached from body. The variable a  keeps a copy of the removed elements when detached method is applied to "p" element and checking it's value "p" is appended to body through a and assigning it to null to maintain toggling effect of attaching and detaching "p" element.
                       
                    
0 Comment(s)