• jQuery Video Tutorials

jQuery detach() Method



The detach() method in jQuery is used to remove matched elements (including all text and child nodes) from the DOM while keeping their data and events intact.

This method retains a copy of the removed elements, which allows them to be reinserted later.

Syntax

Following is the syntax of detach() method in jQuery −

$(selector).detach()

Parameters

This method does not accept any parameters.

Example 1

In the following example, we are using the detach() method to remove the <div> element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("div").detach();
  })
});
</script>
</head>
<body>
<div>
  <p>This is the element to be detached...</p>
</div>
<button>Click</button>
</body>
</html>

When we click the button, it removes the selected element <div> element, including the child nodes.

Example 2

Here, we are using the detach() method to remove and restore the <div> element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  var detachedElement;
  $("#detach-button").click(function(){
    detachedElement = $("div").detach();
  });

  $("#restore-button").click(function(){
    $("body").append(detachedElement);
  });
});
</script>
</head>
<body>
<div>
  <p>This is the element to be detached.</p>
</div>
<button id="detach-button">Remove Element</button>
<button id="restore-button">Restore Element</button>
</body>
</html>

When we execute the program, we will have two buttons: one to remove the detached element and one to restore it. When you click the "Remove Element" button, the div element will be detached and removed from the DOM. Clicking the "Restore Element" button will reinsert the detached element back into the body.

jquery_ref_html.htm
Advertisements