Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 56 ยท Manipulating the DOM

Removing, Replacing, Wrapping

Remove, detach, empty, replace, wrap and clone elements with jQuery, and learn which methods keep event handlers and data and which throw them away.

After inserting content, the next job is changing what is already there: deleting a finished task, swapping a placeholder for the real thing, wrapping an image in a link, or copying a template row. jQuery has a dedicated method for each of these, and the differences between them are small but important. The most important question to ask is always the same: what happens to the event handlers and stored data of the elements I am touching?

Taking things out

.remove() Delete the element, its handlers and its data.
.detach() Take it out but keep handlers and data for later.
.empty() Delete the children, keep the element.
1 / 2

remove, detach and empty

.remove() deletes the selected elements from the page. It also removes everything jQuery attached to them: event handlers added with .on() and values stored with .data(). It returns the removed elements, but they are now plain copies without that extra state.

JavaScript
$(".notice").remove();

You can pass a selector to filter the set: $("li").remove(".done") removes only the list items that have the class done.

.detach() is the same operation with one difference: it keeps the handlers and data. That makes it the right tool when you plan to put the element back, for example while you make many changes to a large piece of the page off-screen.

JavaScript
var $panel = $("#panel").detach();   // gone from the page, still fully alive
// ...change $panel a lot, cheaply...
$panel.appendTo("#container");       // back, handlers intact

.empty() leaves the element itself in place and removes everything inside it (child elements and text), cleaning up their handlers and data as it goes. Use it to clear a list before filling it again. It is safer than .html("") for the same reason, and clearer than .text("").

Method Element stays? Children removed? Handlers and data kept?
.remove() No Yes (with it) No
.detach() No (kept in memory) Kept inside Yes
.empty() Yes Yes No (for the children)
remove, detach and empty

Replacing elements

.replaceWith(content) swaps each selected element for the new content. The old element is removed (so its handlers go too), and the method returns the old element, not the new one.

JavaScript
$("#placeholder").replaceWith("<p class='loaded'>Loaded!</p>");

.replaceAll(target) reads the other way around, just like .appendTo() mirrors .append(): $(content).replaceAll(target). Use whichever sentence order reads better.

Replacing is different from changing the inner content with .html(): the element itself, its attributes and its place in the DOM are swapped out. If you only want to change what is inside, .html() or .text() is the lighter choice, as covered in Getting and Setting Content.

Wrapping elements

Wrapping puts structure around content you already have. All four methods accept an HTML string, a selector, an element or a function.

  • .wrap("<div class='frame'></div>") wraps each selected element in its own copy of the wrapper.
  • .wrapAll("<div class='group'></div>") wraps all selected elements together in a single wrapper, placed where the first one was.
  • .wrapInner("<span class='label'></span>") wraps the contents of each selected element, leaving the element itself in place.
  • .unwrap() removes the parent of each selected element and leaves the element there; call it as .unwrap("div") to remove the parent only if it matches.

If the wrapper you pass has nested elements, jQuery wraps the content around the innermost first child: <div><p></p></div> as a wrapper puts the element inside the <p>.

Wrapping and unwrapping

Press the buttons in different orders to see the structure change. Wrapping is a quick way to add a layout container or a link without touching the original HTML.

Cloning

.clone() makes a deep copy of the selected elements, including their children. By default the copy has no event handlers and no .data() values:

JavaScript
var $copy = $("#row-template").clone();

Pass true to copy handlers and data as well: .clone(true). A second argument, .clone(true, true), also copies them for the elements inside. Use this when a template row already has working buttons.

Two cautions. First, id values are copied too, so remove or replace them: .clone().removeAttr("id"). Second, a clone is not in the page until you insert it, usually with one of the insertion methods. Cloning a hidden template and filling its fields is the standard way to add table rows.

A word about native removal

Everything above only cleans up properly when you use jQuery's methods. If code calls node.remove() or parent.removeChild(node) directly, the DOM element goes, but jQuery's stored data and handler bookkeeping for it may linger in memory. Stay with .remove() and .empty() for any element you attached jQuery state to.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You want to take an element out of the page, edit it, and put it back with its click handlers still working. Which method should remove it?

    detach() removes the element but keeps its handlers and data, so it can be re-inserted fully working. remove() throws that state away.
  2. 2. What does $("#list").empty() do?

    empty() clears the contents, and cleans up their handlers and data, while the element itself stays.
  3. 3. How does .wrapAll() differ from .wrap()?

    wrap makes one wrapper copy per element. wrapAll creates one wrapper that contains all the selected elements.
  4. 4. What does .clone() copy by default?

    A plain clone copies the structure only. Use .clone(true) to copy handlers and data too.
  5. 5. What does .replaceWith() return?

    replaceWith returns the elements that were replaced, which is useful if you want to reuse them.

Summary

  • .remove() deletes elements with their handlers and data; .detach() keeps them for re-insertion.
  • .empty() clears the children of an element and keeps the element.
  • .replaceWith() swaps elements for new content and returns the old ones; .replaceAll() reverses the sentence.
  • .wrap() wraps each element, .wrapAll() wraps the group, .wrapInner() wraps the contents, .unwrap() removes the parent.
  • .clone() copies structure only; .clone(true) also copies handlers and data.
  • Duplicate id values on clones must be removed or changed.
  • Use jQuery removal methods for elements that carry jQuery state.

Next, learn how to change how elements look in CSS and Classes.