Introduction to JQUERY - Detaching Elements using the detach() method

Guest Posts Paolo Nikko Nuñal

Sometimes removing HTML elements using the remove() method does not work on some occasions as you might as well keep some elements on screen. Thanks to the detach() method in JQUERY, you can now select all text and child nodes and keep data and events.

Additionally, the detach() method also keeps a copy of the removed elements that can be reinserted at a later time during your program.

You might be confused with the remove(), and empty() methods but rest assured they may have the same applications like removing, but certainly they don't have the same function.

The remove() method removes the element that includes its data and events.
The empty() method on the other hand, removes only the content of the selected empty, hence the name.




<script src="">
<p>The quick brown fox jumps over</p>
<p>the lazy dog</p>
<button type="button" id="btn-remove">Detach H1 </button>

Once you click on the "remove" button, it will automatically detach all the H1 elements. This is useful if you are planning on removing elements temporarily and want to retrieve them later on in your program. Some of the most common uses of the detach() method is removing a specific element during a process and if the user wants to retrieve the data you can easily call it back and show it on the page.