This post was most recently updated on September 28th, 2017
Definition:
- remove() – Removes all child elements with selected element. In this method you can restore all data but not event handlers of removed elements from the DOM. All data and events related with elements will be removed.
- empty() – Removes all content and child elements from the selected element. This method does not remove selected element.
- 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-empty">empty()</button> <button class="btn-detach">detach()</button> |
CODE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$(document).ready(function(){ $("button.btn-remove").click(function(){ $("#divElement").remove(); }); $("button.btn-empty").click(function(){ $("#divElement").empty(); }); $("button.btn-detach").click(function(){ $("#divElement").detach(); }); }); |
Output:
Explanation: In the above example there are SPAN element and some content inside the DIV element. See there are three buttons remove(), empty(), detach().
When you click on “remove()” button it will remove the yellow box with all content and elements inside the yellow box.
When you click on “empty()” button it will remove all content and child elements inside the yellow box only empty yellow box will display.
When you click on “detach()” button it will remove all content and child elements inside the yellow box and yellow box too but it keeps all data and event handlers of the removed elements which we can reuse it at a later time.
Click here to get more details about remove() and detach() methods.
Good post.