Hide or remove?
Before removing anything, ask whether you really want it gone. .hide() (covered in the effects section) makes an element invisible but leaves it in the page, ready to show again. Removing takes it out of the document entirely. Use removal for things that are finished with: a deleted comment, a closed notification, old search results.
There is also a practical difference for the people using your page. A hidden element is still in the document, so it still takes memory, its handlers still exist, and some code (such as a form submission) still reads its values. A removed element is gone from all of that. On the other hand, removing something a user may want back means rebuilding it later, so a panel that is opened and closed many times is usually better hidden and shown.
.remove()
.remove() takes the selected elements, and everything inside them, out of the page:
<div class="notice" id="n1">Welcome back! <button class="close">×</button></div>
<div class="notice" id="n2">Your trial ends soon. <button class="close">×</button></div>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$(".close").on("click", function () {
$(this).closest(".notice").remove();
console.log("notices left:", $(".notice").length, "| remaining:", $(".notice").attr("id"));
});
</script>notices left: 1 | remaining: n1The traversal pattern from earlier lessons comes back: from the clicked button, go up to its notice, then remove that notice.
You can pass a selector to remove only some of the selected elements:
<ul>
<li class="done">Buy milk</li>
<li>Call Ravi</li>
<li class="done">Pay rent</li>
</ul>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("li").remove(".done");
console.log($("li").length, $("li").text());
</script>1 Call Ravi.empty()
.empty() removes everything inside an element, but keeps the element. It is the right choice for clearing a container before filling it again:
<ul id="results"><li>Old result 1</li><li>Old result 2</li></ul>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
const $results = $("#results").empty();
console.log("children after empty:", $results.children().length, "| still on page:", $("#results").length);
$results.append("<li>New result</li>");
console.log($results.text());
</script>children after empty: 0 | still on page: 1
New result.detach(): remove now, put back later
.remove() also cleans up jQuery's data and event handlers for the removed elements, which prevents memory leaks. That is usually what you want, but it means the element loses its behaviour if you insert it again. .detach() removes elements without cleaning up:
<div id="stage"><button id="btn">Click me</button></div>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
let clicks = 0;
$("#btn").on("click", () => clicks++).data("label", "important");
// detach and re-insert: handler and data survive
const $detached = $("#btn").detach();
$("#stage").append($detached);
$("#btn").trigger("click");
console.log("after detach: clicks =", clicks, "| data =", $("#btn").data("label"));
// remove and re-insert: handler and data are gone
const $removed = $("#btn").remove();
$("#stage").append($removed);
$("#btn").trigger("click");
console.log("after remove: clicks =", clicks, "| data =", $("#btn").data("label"));
</script>after detach: clicks = 1 | data = important
after remove: clicks = 1 | data = undefinedAfter .detach() the click still counted and the data was still there. After .remove() the handler no longer ran and the data was gone, even though the element itself came back.
Use .detach() when you take elements out temporarily, for example to sort a long list away from the page and put it back, or to move a widget between layouts.
Replacing elements
.replaceWith() swaps the selected elements for new content:
<p id="name">Asha Verma</p>
<button id="edit">Edit name</button>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#edit").on("click", function () {
const current = $("#name").text();
$("#name").replaceWith($("<input>", { id: "name", value: current }));
console.log("now an", $("#name").prop("tagName"), "with value", $("#name").val());
});
</script>now an INPUT with value Asha VermaThis "click to edit" pattern turns text into an input. Note that .replaceWith() returns the old (removed) elements, not the new ones, so select the new element again if you need it, as the log line does. .replaceAll() is the swapped twin: $(newContent).replaceAll(target).
Unwrapping text
Sometimes you want to remove a tag but keep what is inside it. .unwrap() and .contents() handle that; the next lesson covers them with wrapping.
Common mistakes
- Removing when you mean to hide, then needing the element back.
- Using
.remove()before re-inserting and losing handlers; use.detach(). - Using
.html("")to clear content. It works, but.empty()states the intent and cleans up jQuery data. - Expecting
.replaceWith()to return the new element.
Exercise
Make a list where each item has a Delete button. Clicking a button removes that item. When the last item is removed, replace the empty list with a paragraph saying Nothing left.
Show one possible answer
<ul id="list">
<li>One <button>Delete</button></li>
<li>Two <button>Delete</button></li>
</ul>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#list button").on("click", function () {
$(this).closest("li").remove();
if (!$("#list li").length) {
$("#list").replaceWith("<p>Nothing left</p>");
}
});
</script>Nothing leftKey points
- .remove() takes elements off the page and throws away their jQuery data and event handlers.
- .empty() removes everything inside an element but keeps the element itself.
- .detach() removes elements but keeps their data and handlers, so you can put them back later.
- .replaceWith() swaps elements for new content; .remove(selector) can filter what is removed.