jQuery replaceWith() Method

Beginner
6 min read
Updated: Oct 2026
5 examples
Live preview

What Is replaceWith()?

.replaceWith(newContent) replaces each matched element with new content (since jQuery 1.2). Target comes first; content is the argument — the reverse of .replaceAll(). A function form was added in 1.4.

Remember
$("p").replaceWith("<b>Paragraph.</b>")
$("div.second").replaceWith("<h2>New heading</h2>")
$("div.third").replaceWith($(".first"))   // move existing node

// same DOM result, reversed syntax:
$("<b>Paragraph.</b>").replaceAll("p")

// returns the removed set — not the new nodes
var $gone = $("#status").replaceWith("<strong>Done</strong>");
NeedUse
Target first, swap out$(target).replaceWith(content)
Content first$(content).replaceAll(target)
Change inside only.html()
Delete without replacement.remove()

How to Use replaceWith()

Select what to remove, pass the replacement, swap them out.

  1. Select the element(s) you want to replace.
  2. Pass new content: HTML string, element, array, jQuery object, or function.
  3. Call .replaceWith(newContent) — each match is swapped.
  4. Remember: the return value is the removed set.
PieceRequired?Role
jQuery collectionYesElements to replace (targets)
newContentYes*HTML, element(s), or jQuery
functionAlt*Per-element replacement (1.4+)
Return—Original removed set

* Pass either newContent or a function, not both.

Pseudocode

Pseudocode
targets = matched elements
content = newContent  // or content = fn.call(each target)

for each t in targets:
    remove t (and its data/events)
    if first target:
        put content in t's place  // move if already in DOM
    else:
        clone content into t's place

return original targets  // removed set, not the new nodes

// Same idea as .replaceAll(), reversed syntax:
// target.replaceWith(content)  ≡  content.replaceAll(target)

Cheat Sheet

Keep these facts handy while swapping elements.

TopicDetail
Syntax.replaceWith(newContent) or .replaceWith(fn)
Since1.2 (content) · 1.4 (function)
vs .replaceAll()Target-first vs content-first
ReturnRemoved set (not replacements)
One matchExisting nodes move
Many matchesClones after the first
CleanupData and events on removed nodes
vs .html()Whole element vs inner content

Live Preview

Run official-style replaceWith actions on a tiny demo tree and see matched elements swap for new content.

Browser demo of .replaceWith() — same idea as the examples below.

Result
Ready — pick an action and run.

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Official Demo: Replace All Paragraphs

Swap every <p> for a bold “Paragraph.” element.

jQuery
// <p>Hello</p><p>cruel</p><p>World</p>
$("p").replaceWith("<b>Paragraph.</b>");
Try It Yourself

How It Works

  1. Select. Every p is in the matched set.
  2. Content. An HTML string builds the bold replacement.
  3. Swap. Each paragraph is removed; bold fills its slot.
  4. Clones. Multiple matches get copies of the replacement.

Example 2 — Official Demo: Replace .second

Replace one middle .inner div with a new heading.

jQuery
// <div class="container">
//   <div class="inner first">Hello</div>
//   <div class="inner second">And</div>
//   <div class="inner third">Goodbye</div>
// </div>
$("div.second").replaceWith("<h2>New heading</h2>");
Try It Yourself

How It Works

  1. One target. Only div.second matches.
  2. New heading. HTML is parsed into an h2.
  3. Whole element. The middle div leaves; the heading takes its place.
  4. Neighbors stay. .first and .third are untouched.

Example 3 — Official Demo: Move an Existing Node

Use one existing element as the replacement — it moves, not clones.

jQuery
// Start: .first Hello, .second And, .third Goodbye
$("div.third").replaceWith($(".first"));
// Result: And, then Hello (moved) — .third is gone
Try It Yourself

How It Works

  1. Select target. div.third will be removed.
  2. Pass content. $(".first") is an existing DOM node.
  3. Move, not clone. Hello leaves its old spot and fills third’s place.
  4. Official rule. Single location → move.

Example 4 — replaceWith vs replaceAll

Same swap; pick target-first or content-first syntax.

jQuery
// Target first
$("#status").replaceWith("<strong>Done</strong>");

// Content first — same DOM result
$("<strong>Done</strong>").replaceAll("#status");
Try It Yourself

How It Works

  1. Select first. replaceWith reads well when the old node is selected.
  2. Build first. replaceAll reads well when the new node is ready.
  3. Same swap. #status is removed; <strong> takes its place.
  4. Return differs. replaceWith gives you the removed set.

Example 5 — Official Demo: Callback + contents()

Replace a container with its own children using the function form (1.4+).

jQuery
// <div class="container">
//   <div class="inner">Scooby</div>
//   <div class="inner">Dooby</div>
//   <div class="inner">Doo</div>
// </div>
$("div.container").replaceWith(function () {
  return $(this).contents();
});
// Children stay; the outer .container is gone
Try It Yourself

How It Works

  1. Function form. jQuery calls your function once per match.
  2. this. Inside, this is the DOM element being replaced.
  3. Return children. .contents() is what replaces the container.
  4. Unwrap effect. Outer shell leaves; kids stay in place.

Edge Cases & Pitfalls

Check these before swapping nodes in real pages.

return

Return is the removed set

Do not expect the new nodes from the return value. Keep a separate reference if you need the replacements.

cleanup

Removed nodes lose data and events

Handlers on matched elements are cleared. Tear down carefully if you need custom cleanup first.

detached

No parent → no effect (1.9+)

On nodes without a parent, .replaceWith() does nothing and still returns the original set.

scope

Whole element, not inner HTML

To change only contents, use .html().

xss

Untrusted HTML is unsafe

Prefer .text() for user strings when building replacement nodes.

Browser Support

.replaceWith() is a core jQuery method (since 1.2; function form 1.4). It needs a browser DOM with jQuery loaded.

✓ jQuery 1.2+ · Browsers only

jQuery .replaceWith()

Works in Chrome, Firefox, Safari, Edge, and other browsers with jQuery. Not for Node.js without a DOM.

100% Browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.replaceWith() Browsers

Bottom line: Use .replaceWith(newContent) in the browser for target-first element swaps. Prefer .replaceAll() when you build the replacement first.

Performance Notes

ApproachCostBest for
.replaceWith(one)LowSingle element swap / move
.replaceWith(many)HigherClones per extra match
.html()Often lowerUpdating inside a kept shell

Prefer one clear replace over many tiny swaps in a loop. If you only need new inner content, .html() is usually cheaper.

Key Takeaways

  • Role: replace each matched element with new content.
  • Syntax: target first — mirror of .replaceAll().
  • Return: the removed set, not the new nodes.
  • Not html: the whole element is swapped, not just its insides.

One line: $(target).replaceWith(content) swaps matched elements for content — target-first twin of .replaceAll().

Frequently Asked Questions

.replaceWith(newContent) removes each matched element and inserts new content in its place. newContent can be HTML, a DOM element, an array, a jQuery object, or a function (since 1.4). Returns the original removed set. Available since jQuery 1.2.
Same DOM result, reversed syntax. Target first: $('p').replaceWith('<b>Hi</b>'). Content first: $('<b>Hi</b>').replaceAll('p'). Prefer replaceWith when the target is already selected.
The original jQuery object for the removed elements — not the new replacements. Since jQuery 1.9 it always returns that original set.
One matched target: an existing replacement node moves. Multiple matched targets: clones for every match after the first.
Data and event handlers on the removed matched nodes are cleaned up. Replacement elements keep their own handlers.
.html() changes what is inside an element; the outer tag stays. .replaceWith() removes the entire matched element and puts the replacement in its place.

Next: jQuery.hasData()

Check whether an element still has any jQuery data stored on it.

hasData() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful