The jQuery detach() method can be used to remove selected elements including its text and nodes. It keeps the data and the events when removing the elements. However, the method keeps a copy of the removed elements from the DOM.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select and detach it with text and nodes. You have to use the element tag name, class name, or id to select. It is a required field. |
jQuery detach() Method to Remove Element
If you want to remove the selected elements, you have to use the method as given below. You have to select the element and use the detach() to delete the element.
Example
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("p").detach(); }); }); </script> <p><em>Welcome to Tutorialdeep!</em> This is my paragraph.</p><br> <button type="button" class="mybtn">Click to Remove Element</button> |
Output
Welcome to Tutorialdeep! This is my paragraph.
When you click the button given above, the method removes the paragraph and its text content. You can click the button given above to insert content em element before the paragraph.
Restore the Removed Element
You can restore the element after you remove it with the detach() method. Use the method as given below in the example. The example first uses the detach() method to remove the element. After that, it can be restored using the restore button.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<script> $(document).ready(function(){ var myvar; $('.btnremove').click(function(){ myvar = $("p").detach(); }); $('.btnrestore').click(function(){ myvar.appendTo("body"); }); }); </script> <p><em>Welcome to Tutorialdeep!</em> This is my paragraph.</p><br> <button type="button" class="btnremove">Click to Remove Element</button> <button type="button" class="btnrestore">Click to Restore Element</button> |
Output
Welcome to Tutorialdeep! This is my paragraph.
Click the remove button first to remove the element. Now, click the restore button to restore back the deleted element from the DOM.
You may also like to read
I hope you like this tutorial on jQuery detach() method. If you have any queries regarding the tutorial, please comment below.
References