
- jQuery - Home
- jQuery - Roadmap
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
jQuery detach() Method
The detach() method in jQuery is used to remove matched elements (including all text and child nodes) from the DOM while keeping their data and events intact.
This method retains a copy of the removed elements, which allows them to be reinserted later.
Syntax
Following is the syntax of detach() method in jQuery −
$(selector).detach()
Parameters
This method does not accept any parameters.
Example 1
In the following example, we are using the detach() method to remove the <div> element −
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").detach(); }) }); </script> </head> <body> <div> <p>This is the element to be detached...</p> </div> <button>Click</button> </body> </html>
When we click the button, it removes the selected element <div> element, including the child nodes.
Example 2
Here, we are using the detach() method to remove and restore the <div> element −
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ var detachedElement; $("#detach-button").click(function(){ detachedElement = $("div").detach(); }); $("#restore-button").click(function(){ $("body").append(detachedElement); }); }); </script> </head> <body> <div> <p>This is the element to be detached.</p> </div> <button id="detach-button">Remove Element</button> <button id="restore-button">Restore Element</button> </body> </html>
When we execute the program, we will have two buttons: one to remove the detached element and one to restore it. When you click the "Remove Element" button, the div element will be detached and removed from the DOM. Clicking the "Restore Element" button will reinsert the detached element back into the body.