Himanshu SharmaSoftware engineer
Let’s talk

jQuery · Lesson 19 of 45

Removing and replacing elements

Take elements off the page with jQuery .remove(), .empty() and .detach(), replace them with .replaceWith(), and know which one keeps data and event handlers.

10 minAdding and removing elementsUpdated 23 October 2026

By the end of this lessonDelete, clear, temporarily take out and replace elements, choosing the method that keeps or discards their data and handlers as needed.

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:

html
<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>
result
notices left: 1 | remaining: n1

The 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:

html
<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>
result
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:

html
<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>
result
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:

html
<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>
result
after detach: clicks = 1 | data = important
after remove: clicks = 1 | data = undefined

After .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:

html
<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>
result
now an INPUT with value Asha Verma

This "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
html
<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>
result
Nothing left

Key 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.

Check yourself

1. Which method clears a list's items but keeps the ul element?
2. You want to take a panel out of the page and insert it again later with its click handlers working. Which method?
3. What does $("li").remove(".done") remove?
4. What is the difference between .hide() and .remove()?