Just as you can add content to the page, jQuery makes it incredibly easy to remove it.
Whether you're deleting a specific row from a table or clearing out a search results box,
there are two main methods to handle deletion: remove() and
empty().
To use these correctly, you must understand the difference in their scope:
Deletes the **selected element** and everything inside it.
$("#container").remove();
Deletes only the **child elements** (keeps the parent container).
$("#container").empty();
The remove() method removes the matched element from the DOM entirely. All
bound events and data associated with the elements are also removed.
$("#div1").remove();
The remove() method also accepts one parameter, which allows you to filter the
elements to be removed. The parameter can be any of the jQuery selector syntaxes.
// Removes all <p> elements with class="test"
$("p").remove(".test");
// Removes all <p> elements with class="test" AND class="demo"
$("p").remove(".test, .demo");
The empty() method does not remove the element itself, but it removes all of
its child nodes (including text nodes). Use this when you want to "clear" a box to put
new content in it later.
// Clears everything inside #results, but #results stays on the page
$("#results").empty();
.empty() once and then .append() new
content, rather than deleting and recreating the main container.
Imagine a notification list where users can "Dismiss All" messages.
$("#dismissAll").click(function() {
// We want to keep the frame but remove all messages
$("#notification-list").empty();
// Or we want to remove specific notifications
$(".notification-item").remove(".read");
});
.hide()
instead of .remove().