Remove and Empty
Delete elements or clear out their contents.
Syntax
$(el).remove(); $(el).empty();Two ways to get rid of content:
.remove()— delete the element itself and everything in it..empty()— keep the element but remove all its children.
Example
Loading editor…
Press Run to see the result.
When to use it
- A todo list removes completed items from the DOM with .remove() when the user ticks a checkbox.
- A multi-file uploader calls .empty() on the file preview container before repopulating it with a new selection.
- A search results panel empties its contents with .empty() before appending the next page of AJAX results.
More examples
Remove a list item on click
.remove() deletes the element and all its children and event handlers from the DOM completely.
<ul id="list">
<li>Item A <button class="rm">Remove</button></li>
<li>Item B <button class="rm">Remove</button></li>
</ul>
<script>
$(function () {
$("#list").on("click", ".rm", function () {
$(this).closest("li").remove();
});
});
</script>Clear a container with .empty()
.empty() removes all child nodes from the container but leaves the container element itself in the DOM.
<div id="results">
<p>Old result 1</p>
<p>Old result 2</p>
</div>
<button id="clear">Clear results</button>
<button id="reload">Reload</button>
<script>
$(function () {
$("#clear").click(function () { $("#results").empty(); });
$("#reload").click(function () {
$("#results").html("<p>New result A</p><p>New result B</p>");
});
});
</script>Remove elements matching a filter
Chaining a selector in .remove() (or targeting before calling it) removes only the matching subset of elements.
<ul id="tasks">
<li class="done">Buy milk ✓</li>
<li>Write report</li>
<li class="done">Send email ✓</li>
</ul>
<button id="clearDone">Clear done</button>
<script>
$(function () {
$("#clearDone").click(function () {
$("#tasks li.done").remove();
});
});
</script>
Discussion