jQuery empty() vs remove()

The jQuery methods empty() and remove() are both used to alter or eliminate content from selected elements within the Document Object Model (DOM), but they serve distinct purposes.

jQuery remove()

The jQuery remove() method, on the other hand, completely removes the selected elements from the DOM, including their content and associated event handlers. This method is used when you want to entirely eliminate an element and all of its descendants.

$("h2").remove();
<h2>Press the button to remove this heading</h2>

Use remove() method when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

run this source code Browser View

Press the button to remove this heading

Full Source
<html> <head> <title>jQuery remove() example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function(){ $("h2").remove(); }); }); </script> </head> <body> <button id="btn">Remove</button> <br> <h2>Press the button to remove this heading</h2> </body> </html>

jQuery empty()

The jQuery empty() method is used to remove all child elements and text content from the selected elements, effectively clearing their content while leaving the elements themselves intact. This is particularly useful when you want to retain the structure of an element but remove its inner content.

$("div").empty();
<div style="height:10%;background-color:green"> Press the button to empty this heading </div>

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.

run this source code Browser View


Press the button to empty this heading
Full Source
<html> <head> <title>jQuery empty() example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function(){ $("div").empty(); }); }); </script> </head> <body> <button id="btn">Empty</button> <div style="height:10%;background-color:green"> Press the button to empty this heading </div> </body> </html>

Conclusion

jQuery empty() focuses on clearing content while keeping the element structure, while remove() takes a more drastic approach by erasing the entire element and its contents from the DOM. The choice between the two depends on whether you want to maintain the element structure or completely eliminate it from the document.