JavaScript Element replaceWith() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance method

What You’ll Learn

Element.replaceWith() is an instance method from the ChildNode API. It replaces the element itself in its parent’s child list with new nodes or strings. Learn the MDN pspan swap, how it differs from replaceChildren(), and five try-it labs.

01

Kind

Instance method

02

Action

Replace self

03

Args

Nodes or strings

04

Returns

undefined

05

vs children

not inner kids

06

Status

Baseline widely

Introduction

Older DOM code often used parent.replaceChild(newNode, oldNode) to swap one element for another. replaceWith() expresses the same idea on the element being removed: call it on the node you want gone, and pass what should take its place.

You can pass elements, other nodes, or plain strings. Strings become Text nodes automatically. After the call, the original element is no longer in the document.

💡
Beginner tip

replaceWith() replaces this element in the parent. replaceChildren() replaces the children inside an element—a different target.

This page is part of JavaScript Element. Related: remove(), after().

Understanding the replaceWith() Method

Calling el.replaceWith(...nodes) removes el from its parent and inserts the new nodes in the same position among siblings.

  • It is an instance method on Element (ChildNode mixin).
  • Arguments can be Node objects or strings (as Text).
  • Multiple arguments insert in the order you pass them.
  • The element you call replaceWith on is removed from the DOM.
  • Return value is undefined (MDN).
  • MDN: replaceWith is unscopable—unavailable inside with.

📝 Syntax

General forms of Element.replaceWith (MDN):

JavaScript
replaceWith(param1)
replaceWith(param1, param2)
replaceWith(param1, param2, /* …, */ paramN)

Parameters

  • param1, …, paramN — a set of Node objects or strings to replace this element with (MDN).

Return value

None (undefined) (MDN).

Exceptions

  • Thrown when the node cannot be inserted at the specified point in the hierarchy (MDN).

Common patterns

JavaScript
const p = document.querySelector("p");
const span = document.createElement("span");

p.replaceWith(span);           // swap element
p.replaceWith("Upgraded");     // swap for text
p.replaceWith(span, " · ");   // several replacements in order

⚡ Quick Reference

GoalCode
Replace elementel.replaceWith(newEl)
Replace with textel.replaceWith("Hello")
Replace with severalel.replaceWith(a, b)
Classic equivalentparent.replaceChild(newNode, el)
Return valueundefined
MDN statusBaseline Widely available (since April 2018)

🔍 At a Glance

Four facts to remember about Element.replaceWith().

Returns
undefined

Original el removed

Baseline
widely

Since April 2018

Target
self

Not children

Strings
→ Text

Auto Text nodes

📋 replaceWith() vs replaceChildren() vs remove()

replaceWith()replaceChildren()remove()
What changesThe element itselfChildren inside elementElement removed only
Inserts replacementYes (args)Yes (args)No
StringsYes (as Text)Yes (as Text)N/A
Return valueundefinedundefinedundefined
Best forSwap this elementSwap inner contentDelete with no replacement

Examples Gallery

Examples follow MDN Element.replaceWith() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN’s pspan swap and text replacement.

Example 1 — Replace With an Element (MDN)

Swap a <p> for a <span> inside a div.

JavaScript
const div = document.createElement("div");
const p = document.createElement("p");
div.appendChild(p);
const span = document.createElement("span");

p.replaceWith(span);

console.log(div.outerHTML);
// "<div><span></span></div>"
Try It Yourself

How It Works

MDN: p is removed from the parent and span takes its place. The <p> no longer appears in outerHTML.

Example 2 — Replace With Text

Pass a string; the browser creates a Text node in place of the element.

JavaScript
const div = document.createElement("div");
const p = document.createElement("p");
p.textContent = "Old";
div.appendChild(p);

p.replaceWith("Upgraded");

console.log(div.textContent); // "Upgraded"
Try It Yourself

How It Works

The paragraph element is gone. A Text node with “Upgraded” sits where p used to be.

📈 Practical Patterns

Multiple replacements, comparisons, and UI upgrades.

Example 3 — Several Nodes in One Call

Replace one element with an element plus trailing text.

JavaScript
const div = document.createElement("div");
const old = document.createElement("p");
old.textContent = "Old";
div.appendChild(old);
const span = document.createElement("span");
span.textContent = "New";

old.replaceWith(span, " (updated)");

console.log(div.innerHTML);
// <span>New</span> (updated)
Try It Yourself

How It Works

Multiple arguments replace the single old element in order: first span, then the text suffix.

Example 4 — vs replaceChildren()

replaceWith swaps the element; replaceChildren swaps inner content.

JavaScript
const box = document.getElementById("box");
const inner = document.getElementById("inner");

// replaceWith — removes #inner element itself
// inner.replaceWith(document.createElement("section"));

// replaceChildren — keeps #inner, swaps its kids
inner.replaceChildren("Only text inside");

console.log(box.innerHTML);
// <div id="inner">Only text inside</div>
Try It Yourself

How It Works

replaceChildren() changes what is inside inner. replaceWith() would remove inner entirely.

Example 5 — Upgrade a Button

Swap an old button element for a new one in place.

JavaScript
const oldBtn = document.getElementById("old-btn");
const newBtn = document.createElement("button");
newBtn.id = "new-btn";
newBtn.textContent = "Continue";
newBtn.type = "button";

oldBtn.replaceWith(newBtn);

console.log(document.getElementById("new-btn") !== null); // true
Try It Yourself

How It Works

A common pattern: replace a stale control with a freshly built element without touching the parent container manually.

🚀 Common Use Cases

  • Swapping an outdated button or card for a freshly built element.
  • Replacing a placeholder node with real content after data loads.
  • Upgrading a custom element or widget in place without touching the parent.
  • Replacing an element with plain text when markup is no longer needed.
  • Expressing parent.replaceChild(newNode, oldNode) on the node being removed.
  • Teaching the difference between replacing self vs replacing children.

🧠 How replaceWith() Swaps Elements

1

Start from an element with a parent

You call el.replaceWith(...) on the node you want removed.

Target
2

Normalize arguments

Strings become Text nodes; existing nodes may detach from their old place.

Prepare
3

Remove and insert in one step

The browser removes el and inserts new nodes in the same sibling position.

Replace
4

DOM updated; return undefined

The original element is gone—check outerHTML or query for the new node.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available since April 2018).
  • replaceWith() replaces the element itself, not its children.
  • Return value is always undefined.
  • Invalid hierarchy can raise HierarchyRequestError.
  • MDN: replaceWith is unscopable—unavailable inside a with statement.
  • Same ChildNode family: before(), after(), remove(), replaceChildren().
  • Related: replaceChild(), children, JavaScript hub.

Browser Support

Element.replaceWith() is Baseline Widely available (MDN: across browsers since April 2018). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.replaceWith()

Safe for production. Replace an element with nodes or strings using a modern ChildNode API.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Not supported · Use replaceChild polyfill pattern
No
replaceWith() Excellent

Bottom line: Prefer replaceWith() when you think “swap this element for something else.” Use replaceChildren() to change inner content only. Use remove() when you need no replacement. Strings become Text nodes automatically.

Conclusion

Element.replaceWith() is the modern way to swap an element for new nodes or text—one or several at once. It returns undefined and removes the original element from the DOM.

Continue with replaceChildren(), remove(), replaceChild(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Call replaceWith() on the element you want gone
  • Pass strings when you need Text nodes quickly
  • Use replaceChildren() for inner content only
  • Build the replacement node before calling replaceWith
  • Verify with outerHTML or querySelector

❌ Don’t

  • Expect a returned node (it is undefined)
  • Confuse replacing self with replacing children
  • Assume IE supports replaceWith() without a fallback
  • Forget that invalid trees can throw HierarchyRequestError
  • Hold stale references to the removed element after the swap

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.replaceWith()

Swap an element for nodes or text—one call, same sibling position.

5
Core concepts
📄 02

Target

this element

Self
✍️ 03

Strings

become Text

Coerce
04

Baseline

widely available

Status
05

Classic

replaceChild

DOM

❓ Frequently Asked Questions

It replaces this element in its parent's children list with the specified Node objects or strings (MDN). Strings become Text nodes.
No. MDN marks Element.replaceWith() as Baseline Widely available (across browsers since April 2018). It is not Deprecated, Experimental, or Non-standard.
Nothing useful — the return value is undefined (MDN). The original element is removed from the DOM.
replaceWith() replaces the element itself. replaceChildren() replaces only the children inside an element.
Yes. replaceWith(node1, node2, …) inserts all arguments in place of the element you call it on (MDN).
Yes. MDN: replaceWith() is not available inside a with statement — use el.replaceWith(...) instead.
Did you know?

replaceWith() comes from the ChildNode mixin—the same family as before(), after(), and remove(). MDN also notes it is unscopable, so it is not available inside a with statement.

Next: requestFullscreen()

Learn how to expand an element to fullscreen mode.

requestFullscreen() →

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.

8 people found this page helpful