jQuery detach()

The jQuery remove() method removes the elements as well as its data and events. While the jQuery empty() method removes only the content from the selected elements. The jQuery detach() method is also used to serve the purpose of removal. The feature that makes this method unique from the rest two is that, this method saves a copy of the removed elements to reinsert them if needed later.

The jQuery detach() method removes the selected elements but keeps data and events.

Syntax:

$(selector).detach()

Example1:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").detach();
});
});
</script>
</head>
<body>
<p>Hello Guys!</p>
<button>Click me</button>
</body>
</html>

Example2:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("body").append($("#p1").detach());
});
$("#btn2").click(function(){
$("body").append($("#p2").remove());
});
$("#btn2").click(function(){
$("body").append($("#p3").empty());
});
});
</script>
</head>
<body>
<p id="p1">Hey!</p>
<p id="p2">Hello!</p>
<p id="p3">Hii!</p>
<button id="btn1">Detach and append</button>
<button id="btn2">Remove and append</button>
<button id="btn2">Empty and append</button>
</body>
</html>