The jQuery detach() method removes the selected elements but keeps the data and events. This method also keeps the copy of removed elements which can reinserted whenever needed.
Note: If you want to remove the elements along with the data and events, use remove() method instead.
If you only want to remove the content of the selected elements and do not want the selected elements to be removed, then use empty() method.
Syntax of detach() method
$(selector).detach()
Example 1: jQuery detach method – remove all p elements
This is a simple example of detach(). Here, we are removing all paragraphs (p elements) using detach() method.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").detach();
});
});
</script>
</head>
<body>
<p>Hey, there!</p>
<p>Welcome to BeginnersBook.com.</p>
<p>Your favourite tutorial site.</p>
<button>Click here to detach all p elements</button>
</body>
</html>
Output:
Before button click:
After button click:
Example 2:jQuery detach() – remove and restore an element
In the following example, we are creating a toggle between detach and restore using detach() and prepend() methods.
When detach() method is used to remove the selected element, it returns a copy of the removed element. This copy is stored in var x
and later we reattached the copy of remove element to the body using prepend() method.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var x;
$("#b1").click(function(){
x = $("p").detach();
});
$("#b2").click(function(){
$("body").prepend(x);
});
});
</script>
</head>
<body>
<p>Hey, there!</p>
<p>Welcome to BeginnersBook.com.</p>
<p>Your favourite tutorial site.</p>
<button id="b1">Detach p elements</button>
<button id="b2">Restore p elements</button>
</body>
</html>
Output:
Before clicking any button:
After clicking “Detach p elements” button:
After clicking “Restore p elements” button: