jQuery detach() Method
jQuery detach() method remove the selected elements including all child elements.
jQuery detach() method is the same as remove() method, except that detach() method keeps all jQuery data and events associated with the removed elements.
jQuery detach() method useful when removed elements will be reinserted into the DOM at a later time.
Syntax
This syntax represent to the detach() method
$(selector).detach( selector );
Parameter | Type | Description |
---|---|---|
selector | Selector | Optional. A selector expression that filter the matched elements to be removed. |
Example: detach() method with no argument
Here, in this example detach() method execute on selected elements when click on button.
$(document).ready(function(){
$("button").click(function(){
$("#p2").detach();
});
});
Example: detach() method with an argument
How to pass selector argument on detach() method.
$(document).ready(function(){
$("button").click(function(){
$("p").detach("#p2");
});
});
Example: Remove and restore an element
How to detach and restore an element using detach() method.
$(document).ready(function(){
var ele;
$(".detach").click(function(){
ele = $("#p2").detach();
});
$(".restore").click(function(){
$("p").append(ele);
});
});