This post was most recently updated on September 26th, 2017
Definition:
- remove() – Removes all child elements with selected element. In this method you can restore all data but not event handlers of the removed elements from the DOM. All data and events related with elements will be removed.
- detach() – Removes all child elements with selected elements. Even though it keeps all data and event handlers of the removed elements. This method is preferred to remove elements but it keeps copy of the removed elements which we can reuse at a later time.
Example:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div id="divElement" style="padding:10px; background-color:yellow; border:1px solid #000000; width:300px; height:150px;"> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div><br/> <button class="btn-remove">remove()</button> <button class="btn-detach">detach()</button> <button class="btn-attach">attach</button> |
CODE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
$(document).ready(function(){ var contentWrapper = $("#divElement"); $("#divElement").click(function(){ alert("Yellow content box"); }); $("button.btn-remove").click(function(){ $("#divElement").remove(); }); $("button.btn-detach").click(function(){ $("#divElement").detach(); }); $("button.btn-attach").click(function(){ $("#attachWrapper").html(contentWrapper); }); }); |
Output:
Explanation: In the above example there are SPAN element and some content inside the DIV element which is a “Yellow Box” and next to that is an empty “Red Box”. See there are three buttons remove(), detach() and attach.
Before click on any buttons click on “Yellow Box” you will get alert message “Yellow content box”. On the “Yellow Box” there is a click event with alert message. Now refresh browser to check button events.
To check difference between remove() and detach() methods follow the steps below:
First click on remove() button it will remove the Yellow box with inside elements data and events.
Then click on attach() you can see the removed “Yellow Box” attached inside the “Red Box” with content.
Now remember when you click on the “Yellow Box” there was an alert message “Yellow content box” click on yellow box to get this message again, you will not get alert message because remove() method removed event handlers from the selected elements.
Now refresh page and click on detach() button it will remove “Yellow Box”.
Then click on attach button “Yellow Box” will attach inside the “Red Box”.
Now click on “Yellow Box” you will get alert message “Yellow content box”