jQuery Remove Elements
Sometimes you need to take things off the page instead of putting them on. jQuery gives you two handy tools for this: remove() deletes an element entirely, and empty() clears out everything inside an element while keeping the element itself.
Removing content with jQuery
When a user closes a message, deletes a to-do item, or clears a list, you are removing elements from the page. jQuery makes this a one-line job. The trick is knowing whether you want the element gone completely, or just its contents wiped out.
- remove() - deletes the selected element and everything inside it.
- empty() - keeps the selected element but removes all of its child nodes and text.
- remove(selector) - lets you delete only the matched elements that also match a filter.
The remove() method
Calling remove() takes the element out of the DOM along with any content and any event handlers or data attached to it. After this runs, the element no longer exists on the page.
Delete an element completely
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="notice">This is a notice message.</div>
<button id="deleteBtn">Delete</button>
<script>
$("#deleteBtn").click(function () {
$("#notice").remove();
});
</script>
</body>
</html>The empty() method
Use empty() when you want to keep a container around but clear whatever is inside it. This is common when you refresh a list or reset an area before adding new content.
Clear the inside of a container
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="items">
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>
<button id="clearList">Clear list</button>
<script>
$("#clearList").click(function () {
$("#items").empty();
});
// <ul id="items"> stays on the page, but all <li> children are gone
</script>
</body>
</html>Remove only certain elements with a filter
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p>Keep this paragraph.</p>
<p class="draft">This draft paragraph will be removed.</p>
<p>Keep this one too.</p>
<script>
// Remove paragraphs that have the class "draft"
$("p").remove(".draft");
</script>
</body>
</html>Exercise: jQuery Remove Elements
What is the core difference between .remove() and .empty()?