Home »
jQuery »
jQuery DOM Manipulation Methods
jQuery detach() Method
jQuery | detach() Method: Learn about the jQuery detach() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 15, 2022
detach() Method
When we want to remove some content from the web page, we can use different methods of jQuery – remove(), empty(), detach(), etc. These all have some minor differences amongst them but overall do the same job. Therefore, let's have a look at the detach() method. This method just removes the text of the element selected and all of its related child nodes. This method does not delete the data and the event handlers attached to it. It basically helps to create a copy that the user can attach anywhere else whenever needed.
detach() Method Syntax
$('selector').detach();
This method does not take any parameter, we just need to specify the selector for the targeted element. It will return the selected element but without the child nodes and text content. The below given example explains the usage of the detach() method. When the detach button is clicked, it will remove the content of that particular selector.
jQuery detach() Method Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.bold{
font-size: larger;
font-weight: bolder;
color: green;
}
.color{
font-size: larger;
font-weight: bolder;
color:darkblue;
}
</style>
<title>Document</title>
</head>
<body>
<h2>jQuery - Detach</h2>
<p>Click the button to detach some of the selected elements.</p>
<button>Detach</button>
<hr>
<p class="bold">This is sentence in green.</p>
<div class="color">This is sentence in blue.</div>
<h4 class="bold">This is sentence in green.</h4>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function(){
$('.color').detach();
})
});
</script>
</html>
Output: