JavaScript Node replaceChild() Method

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

What You’ll Learn

The Node.replaceChild() method swaps one child for another on a parent. Learn the unusual new before old argument order, what happens when the new node is already in the tree, how the return value is the old child, and how this pairs with removeChild() and appendChild().

01

Kind

Instance method

02

Args

new, then old

03

Returns

oldChild

04

Moves

Existing newChild

05

Alt

replaceWith()

06

Status

Baseline widely

Introduction

Sometimes you do not only remove a child—you put something else in the same spot. parent.replaceChild(newChild, oldChild) does that in one step: the old child leaves, the new child takes its place among the siblings.

MDN highlights two beginner traps: the parameter order is new first, old second, and if newChild already lives elsewhere in the document, the browser moves it (it is removed from the old location first).

💡
Beginner tip

For elements only, oldChild.replaceWith(newChild) often reads more clearly. Keep replaceChild when you already hold the parent or follow classic Node tutorials.

Understanding replaceChild()

Call it on the parent. Pass the node that should appear, then the child that should leave. Get the old child back as the return value.

  • SwapnewChild takes oldChild’s place.
  • Order(newChild, oldChild)—new before old.
  • Return — the replaced node (same as oldChild).
  • Move — an already-attached newChild is relocated, not cloned.

📝 Syntax

JavaScript
const replaced = parentNode.replaceChild(newChild, oldChild);

Parameters

  • newChild — The node that will replace oldChild. Warning (MDN): if it is already in the DOM, it is removed from its current position first.
  • oldChild — The child of this parent that will be replaced.

Return value

The replaced Node—the same object as oldChild.

Exceptions

  • NotFoundErroroldChild is not a child of the node you called.
  • HierarchyRequestError — the swap would break DOM rules (for example a cycle, wrong node type, or invalid document structure).

⚖️ replaceChild() vs Element.replaceWith()

parent.replaceChild(new, old)old.replaceWith(new)
Called onParentThe old element
Argument orderNew, then oldNew only (old is this)
Return valueThe old childundefined
Works onAny Node child types allowed by DOMElements (and can take multiple nodes)

⚡ Quick Reference

GoalCode
Replace a childparent.replaceChild(newChild, oldChild)
Remember orderNew first, old second
Keep the old nodeconst old = parent.replaceChild(neu, old)
Via parentNodeold.parentNode.replaceChild(neu, old)
Modern element APIoldChild.replaceWith(newChild)
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about Node.replaceChild().

Returns
oldChild

The replaced node

Baseline
widely

Since July 2015

Order
new, old

Easy to reverse

newChild in DOM
moves

Not cloned

Examples Gallery

Examples follow MDN Node.replaceChild() ideas. Use View Output or Try It Yourself.

📚 Getting Started

Classic replacement and the new-before-old order.

Example 1 — Replace a Span (MDN Style)

Build a new span, then swap it for the existing child.

JavaScript
const parentDiv = document.createElement("div");
const sp2 = document.createElement("span");
sp2.id = "childSpan";
sp2.textContent = "foo bar";
parentDiv.appendChild(sp2);

const sp1 = document.createElement("span");
sp1.id = "newSpan";
sp1.appendChild(document.createTextNode("new replacement span element."));

parentDiv.replaceChild(sp1, sp2);

console.log(parentDiv.firstChild.id);          // "newSpan"
console.log(parentDiv.firstChild.textContent); // "new replacement span element."
console.log(parentDiv.contains(sp2));          // false
Try It Yourself

How It Works

The parent keeps one child slot: sp1 is inserted where sp2 was. The old span is detached.

Example 2 — Remember: New Before Old

Write the call as replaceChild(newThing, oldThing).

JavaScript
const list = document.createElement("ul");
const oldItem = document.createElement("li");
oldItem.textContent = "Old";
list.appendChild(oldItem);

const newItem = document.createElement("li");
newItem.textContent = "New";

// Correct: new first, old second
list.replaceChild(newItem, oldItem);

console.log(list.firstChild.textContent); // "New"
console.log(list.childNodes.length);      // 1
Try It Yourself

How It Works

Reversing the arguments is a common bug. Say it out loud: “replace with the new child, remove the old child.”

📈 Moves, Returns & Errors

Relocate an existing node, reuse oldChild, handle NotFoundError.

Example 3 — New Child Already in the DOM Moves

MDN: an existing node is removed from its old place, then inserted.

JavaScript
const a = document.createElement("div");
const b = document.createElement("div");
const mover = document.createElement("p");
mover.textContent = "Mover";
const target = document.createElement("span");
target.textContent = "Target";

a.appendChild(mover);
b.appendChild(target);

b.replaceChild(mover, target);

console.log(a.contains(mover)); // false (moved away)
console.log(b.firstChild.textContent); // "Mover"
console.log(b.contains(target)); // false
Try It Yourself

How It Works

There is still only one mover object. It leaves a and replaces target inside b.

Example 4 — Return Value Is the Old Child

Store the return value if you still need the replaced node.

JavaScript
const box = document.createElement("div");
const oldNode = document.createElement("em");
oldNode.textContent = "Old";
box.appendChild(oldNode);

const neu = document.createElement("strong");
neu.textContent = "New";

const replaced = box.replaceChild(neu, oldNode);

console.log(replaced === oldNode);   // true
console.log(replaced.textContent);   // "Old"
console.log(box.firstChild.tagName); // "STRONG"
Try It Yourself

How It Works

Like removeChild, the old node is not destroyed—you get it back and can append it somewhere else later.

Example 5 — Wrong Parent Throws NotFoundError

MDN: oldChild must be a child of the node you call.

JavaScript
const parent = document.createElement("div");
const other = document.createElement("div");
const orphan = document.createElement("span");
other.appendChild(orphan);

const neu = document.createElement("b");

try {
  parent.replaceChild(neu, orphan); // orphan is not parent's child
} catch (err) {
  console.log(err.name); // "NotFoundError"
}
Try It Yourself

How It Works

Always call replaceChild on the actual parent of oldChild—or use oldChild.parentNode.replaceChild(...).

🚀 Common Use Cases

  • Swapping a placeholder element for real content in the same position.
  • Updating a list item without rebuilding the whole list.
  • Moving a node from one parent into another child slot via replacement.
  • Teaching classic DOM mutation next to appendChild / removeChild.
  • Keeping a reference to the old child for undo or history UI.

🔧 How It Works

1

Pass new, then old

Verify oldChild belongs to this parent.

Args
2

Relocate if needed

If newChild is elsewhere in the DOM, remove it first.

Move
3

Swap in place

newChild occupies oldChild’s sibling position.

Replace
4

Return oldChild

Reuse it, store it, or let it be garbage-collected.

📝 Notes

Universal Browser Support

Node.replaceChild() is Baseline Widely available across modern browsers (MDN: since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline · Widely available

Node.replaceChild()

Safe, long-standing API for swapping a child in place on its parent.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Long-standing support in legacy IE
Full support
replaceChild() Excellent

Bottom line: Replaces oldChild with newChild; returns oldChild; moves newChild if already in the DOM.

Conclusion

Node.replaceChild() swaps children on a parent: new node in, old node out (and returned). Memorize (newChild, oldChild), remember that existing nodes move, and consider replaceWith when you already hold the old element.

Continue with selectstart, removeChild(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Say “new, then old” when writing the call
  • Call it on the real parent of oldChild
  • Store the return value if you need the old node
  • Expect moves when reusing a live DOM node as newChild
  • Prefer replaceWith for simple element swaps

❌ Don’t

  • Reverse the argument order by habit
  • Assume newChild is cloned—it is moved
  • Replace with a node that would create a DOM cycle
  • Confuse DOM Node with the Node.js runtime
  • Forget NotFoundError when parents do not match

Key Takeaways

Knowledge Unlocked

Five things to remember about replaceChild()

Swap in place—new first, old second.

5
Core concepts
📝 02

new, old

order matters

Args
📤 03

Returns old

reusable

Return
🚀 04

Moves live

newChild

DOM
⚠️ 05

Watch errors

NotFound / Hierarchy

Safety

❓ Frequently Asked Questions

It replaces one child of a parent with another node. Call it on the parent: replaceChild(newChild, oldChild). It returns the replaced node (the same as oldChild).
No. MDN marks Node.replaceChild() as Baseline Widely available (since July 2015). It is a standard DOM method — not Deprecated, Experimental, or Non-standard.
MDN notes the order is unusual: newChild first, oldChild second. Remember “put the new one in, take the old one out.” Element.replaceWith() can be easier to read for elements.
MDN warns that if the new node is already present somewhere else in the DOM, it is first removed from that position, then inserted in place of oldChild.
NotFoundError if oldChild is not a child of the parent you called. HierarchyRequestError when the replacement would violate DOM tree rules (cycles, wrong node types, invalid document structure).
If you already have the old element and only need to swap it, oldChild.replaceWith(newChild) reads more naturally. Use replaceChild when you work from the parent or need classic Node API patterns.
Did you know?

MDN calls out the argument order as unusual on purpose—many developers instinctively write “old, then new.” Saying “replace with X, remove Y” (new, old) once while coding saves a surprising number of runtime mistakes.

Next: selectstart

Learn the Selection API event that fires when selection starts.

selectstart →

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.

5 people found this page helpful