jQuery detach()
method is the same as .remove()
, except that detach() keeps all jQuery data associated with the removed elements. It is useful when removed elements are to be reinserted into the DOM at a later time.
detach() Syntax:
$(selector).detach();
Let see the differences with an example. I have created a div element with some text and assigned hover event to this element. This hover event basically add/remove CSS class to the div.
Below the differences with an example. i've created a div element with some text and assigned hover event to this element. This hover event basically add/remove CSS class to the div.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery detach()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.highlight{font-size:18px;color:#11a286}
</style>
<p><b>remove()</b></p>
<form>
<div id="dvParent">
<div id="divjQuery">lorem ipsum dolor sit.</div>
</div>
<br/>
<input type='button' id='btnRemove' Value='Remove Div' />
<input type='button' id='btnAdd' Value='Add Div' />
<br/><br/>
</form>
<script>
$(document).ready(function() {
var divjQuery = null;
$('#btnAdd').attr('disabled','disabled');
$("#divjQuery").hover(function() {
$(this).addClass('highlight');
}, function() {
$(this).removeClass('highlight');
});
$('#btnRemove').click(function() {
divjQuery = $("#divjQuery").remove();
$(this).attr('disabled','disabled');
$('#btnAdd').removeAttr('disabled');
});
$('#btnAdd').click(function() {
$("#dvParent").html(divjQuery);
$(this).attr('disabled','disabled');
$('#btnRemove').removeAttr('disabled');
});
});
</script>
<p><b>detach()</b></p>
<form>
<div id="divParent">
<div id="divjQueryDetach">lorem ipsum dolor sit. </div>
</div>
<br/>
<input type='button' id='btnDetach' Value='Detach Div' />
<input type='button' id='btnAttach' Value='Re-attach Div' />
<br/><br/>
</form>
<script>
$(document).ready(function() {
var divjQueryDetach = null;
$('#btnAttach').attr('disabled','disabled');
$("#divjQueryDetach").hover(function() {
$(this).addClass('highlight');
}, function() {
$(this).removeClass('highlight');
});
$('#btnDetach').click(function() {
divjQueryDetach = $("#divjQueryDetach").detach();
$(this).attr('disabled','disabled');
$('#btnAttach').removeAttr('disabled');
});
$('#btnAttach').click(function() {
$("#divParent").html(divjQueryDetach);
$(this).attr('disabled','disabled');
$('#btnDetach').removeAttr('disabled');
});
});
</script>
</body>
</html>