JavaScript Node replaceChild() Method

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

What Is replaceChild()?

Node.replaceChild(newChild, oldChild) replaces one child of a parent with another node and returns the replaced node (same as oldChild) (MDN).

Baseline · Widely available: not Deprecated, Experimental, or Non-standard (since July 2015).

Warning: if newChild is already in the DOM, it is moved (removed from its old place first), not cloned (MDN).

Note: argument order is unusual — newChild first, oldChild second. Element.replaceWith() often reads more clearly for elements (MDN).

Remember
parent.replaceChild(newChild, oldChild)  →  oldChild

order: NEW first, OLD second
newChild already in DOM → moved, not cloned

MDN pattern:
  parent.replaceChild(sp1, sp2)
UsePrefer
Swap from known parentparent.replaceChild(newNode, oldNode)
Have the old element onlyoldNode.replaceWith(newNode)
Remove without replacingremoveChild()

How to Use replaceChild()

Call it on the parent: new node first, old child second. Keep the return value if you need the old node.

  1. Get the parent and the oldChild that belongs to it.
  2. Create or locate newChild.
  3. Call parent.replaceChild(newChild, oldChild).
  4. Store the return value if you want to reuse the old node.
PieceRequired?Role
Receiver parentYesCurrent parent of oldChild
newChildYesNode that takes oldChild’s place
oldChildYesChild to replace (must belong to parent)
Return value—The same oldChild node

Pseudocode

Pseudocode
if oldChild.parent is not this node:
  throw NotFoundError

if replacement would break DOM rules:
  throw HierarchyRequestError

if newChild is already in the tree:
  detach newChild from its current parent

put newChild where oldChild was
detach oldChild
return oldChild

Cheat Sheet

Keep these facts handy when swapping children in the tree.

TopicDetail
Syntaxparent.replaceChild(newChild, oldChild)
Arg orderNew first, old second (unusual)
ReturnsThe replaced oldChild
Already in DOM?newChild is moved, not cloned
NotFoundErroroldChild is not a child of that parent
HierarchyRequestErrorInvalid tree (cycle, wrong types, bad document shape)
Modern alternativeoldChild.replaceWith(newChild)
Status (MDN)Baseline Widely available

Live Preview

Swap a child, check argument order, move a node from another parent, or read the returned old node.

Browser demo of Node.replaceChild() — swap, move, or reuse the returned node.

Result
Loading…

JavaScript Examples

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

Example 1 — Basic Swap (MDN)

Replace an existing span with a new span under the same parent.

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

  1. Build the parent and old child. sp2 must belong to parentDiv.
  2. Create the replacement. sp1 is the new child.
  3. Call replaceChild(sp1, sp2). New first, old second.
  4. Old leaves the tree. contains(sp2) is false.

Example 2 — Argument Order

Remember: new child first, old child second.

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";

list.replaceChild(newItem, oldItem);

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

How It Works

  1. Start with one list item. That is oldItem.
  2. Pass new, then old. Reversing them would throw or behave wrongly.
  3. Only one child remains. Length stays 1 — swap, not append.
  4. Text is “New”. The replacement sits in the same slot.

Example 3 — Move an Existing Node

If newChild is already in the DOM, it is moved — not cloned.

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
console.log(b.firstChild.textContent); // "Mover"
console.log(b.contains(target));    // false
Try It Yourself

How It Works

  1. Mover starts under A. Target starts under B.
  2. Replace target with mover. Browser detaches mover from A first (MDN).
  3. A no longer contains mover. Same node object, new parent.
  4. Target is out. Returned/old node leaves B.

Example 4 — Reuse the Returned Node

The return value is the same object as oldChild — keep it to reappend.

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

  1. Swap em for strong. Box now shows New.
  2. Return equals oldNode. Same reference (MDN).
  3. Text is still “Old”. The node object survives outside the tree.
  4. You can append replaced elsewhere. Reuse without recreating.

Example 5 — Guard NotFoundError

oldChild must be a child of the parent you call — otherwise it throws.

JavaScript
function safeReplace(parent, newChild, oldChild) {
  if (oldChild.parentNode !== parent) {
    return "skip: oldChild not under this parent";
  }
  parent.replaceChild(newChild, oldChild);
  return "replaced";
}

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

console.log(safeReplace(parent, neu, orphan));

const child = document.createElement("span");
parent.appendChild(child);
console.log(safeReplace(parent, neu, child));
Try It Yourself

How It Works

  1. Check ownership first. Avoids NotFoundError (MDN).
  2. Orphan lives under other. First call is skipped.
  3. Append a real child. Second call succeeds.
  4. Also watch HierarchyRequestError. Cycles and illegal document shapes throw too.

Edge Cases & Pitfalls

Check these before calling replaceChild() in UI swaps or list updates.

order

New before old

Unlike many APIs, the replacement comes first. Flipping args is a common beginner bug (MDN).

move

newChild is moved

If it already has a parent, it leaves that parent. You do not get a clone (MDN).

parent

Wrong parent → NotFoundError

oldChild must be a direct child of the node you call on.

modern

replaceWith() may read better

When you already have the old element, old.replaceWith(neu) avoids the odd argument order (MDN).

Browser Support

Node.replaceChild() is Baseline Widely available (MDN, since July 2015). Classic DOM swap — safe everywhere.

✓ Baseline · Widely available

Node.replaceChild()

Supported across Chrome, Firefox, Safari, Edge, Opera, and legacy IE. Returns the old child; throws on invalid trees or wrong parent.

99% Browser support
Google Chrome replaceChild() · full support
Full support
Microsoft Edge replaceChild() · Chromium
Full support
Apple Safari replaceChild() · full support
Full support
Mozilla Firefox replaceChild() · full support
Full support
Opera replaceChild() · full support
Full support
Internet Explorer replaceChild() · legacy
Legacy support
Node.replaceChild() Excellent

Bottom line: Use freely. Mind new-before-old order, and prefer Element.replaceWith() when you already hold the old element.

Performance Notes

ApproachCostBest for
Replace one childCheapTargeted UI swaps
Move existing nodeCheapReorder without cloning
Replace all childrenOften simplerreplaceChildren() when clearing/rebuilding

Prefer a single replaceChild for one swap. For wiping and rebuilding a container, replaceChildren() is often clearer.

Key Takeaways

  • Role: put newChild where oldChild was and return the old node.
  • Order: new first, old second — easy to reverse by mistake.
  • Move: an in-tree newChild is relocated, not cloned.
  • Errors: wrong parent → NotFoundError; illegal tree → HierarchyRequestError.

One line: parent.replaceChild(newChild, oldChild) swaps one child and hands back the old node.

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.

Next: selectstart Event

Learn how the selectstart event fires when a user starts selecting text.

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

10 people found this page helpful