The jQuery detach() method is used to remove the selected elements, including all texts and child nodes and keeps only data and events.
This method saves a copy of the removed elements to reinsert them whenever they needed later.
There are some other methods also which are used to remove elements e.g. jQuery remove() method, jQuery empty() method etc. But there is a little difference among them.
jQuery remove() method: This method is used to remove the elements as well as its data and events.
jQuery empty() method: This method is used to remove only the content from the selected elements.
Syntax:
$(selector).detach()
Let's take an example to demonstrate the effect of jQuery detach() method.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").detach(); }); }); </script> </head> <body> <p>Hello Guys!</p> <p>This is rookienerd.com</p> <button>Click here to detach all p elements</button> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>detach demo</title> <style> p { background: lightpink; margin: 6px 0; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p>Hello Guys!</p> <p>This is rookienerd.com</p> <button>Click here to Attach/detach all p elements. </button> <script> $( "p" ).click(function() { $( this ).toggleClass( "off" ); }); var p; $( "button" ).click(function() { if ( p ) { p.appendTo( "body" ); p = null; } else { p = $( "p" ).detach(); } }); </script> </body> </html>
Let's take an example to clear the difference between detach() and remove() method:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("body").append($("#p1").detach()); }); $("#btn2").click(function(){ $("body").append($("#p2").remove()); }); $("p").click(function(){ $(this).animate({fontSize: "+=1px"}) }); }); </script> </head> <body> <p id="p1"><b>This paragraph will keep its click event even after it is moved.</b></p> <p id="p2">This paragraph will not keep its click event after it is moved.</p> <button id="btn1">Detach and append p element</button> <button id="btn2">Remove and append p element</button> </body> </html>