JavaScript Document replaceChildren() Method

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

What You’ll Learn

document.replaceChildren() is an instance method from the ParentNode API. It replaces every child of the Document with a new set of nodes or strings (see MDN Document: replaceChildren()). Learn MDN’s empty-document pattern, building roots on new Document(), HierarchyRequestError, how it compares to Element.replaceChildren(), and five try-it labs.

01

Kind

Instance method

02

Args

0+ nodes/strings

03

Returns

undefined

04

Empty

No arguments

05

UI tip

Use Element

06

Status

Baseline

Introduction

Everyday tutorials empty a list with list.replaceChildren() or rebuild a panel with panel.replaceChildren(newHeading, newPara). Those calls use Element.replaceChildren(). Document.replaceChildren() is the same ParentNode method, but the target is the Document node itself — not <body>.

MDN highlights a convenient empty pattern: call document.replaceChildren() with no arguments, then document.children is an empty HTMLCollection.

💡
Beginner tip

Do not call document.replaceChildren() with no args on the live page you are viewing — it removes the page’s root <html>. Practice on new Document(), or use document.body.replaceChildren(...) / el.replaceChildren(...) for UI work.

Related tutorials: Document constructor, Element.replaceChildren(), Document.append(), Document.prepend().

Understanding document.replaceChildren()

An instance method on every Document (ParentNode mixin).

  • Target — the Document node (not body or head).
  • Arguments — zero or more Node objects or strings (MDN).
  • No args — empties the Document of all child nodes (MDN).
  • Strings — become Text nodes (when allowed by the tree).
  • Returnsundefined (MDN).
  • ExceptionsHierarchyRequestError if the node tree constraints are violated (MDN).
  • Everyday UI — prefer Element.replaceChildren() on a container.

📝 Syntax

General forms of Document.replaceChildren (MDN):

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

Parameters

  • param1, …, paramN — a set of Node objects or strings to replace the Document’s existing children with. If none are specified, the Document is emptied of all child nodes (MDN).

Return value

None (undefined) (MDN).

Exceptions

  • HierarchyRequestError DOMException — thrown if the constraints of the node tree are violated (MDN).

MDN empty sample

JavaScript
document.replaceChildren();
document.children; // HTMLCollection []

⚡ Quick Reference

GoalCode / note
Empty a Documentdoc.replaceChildren() (MDN)
Set a new rootdoc.replaceChildren(htmlElement)
Empty a UI boxbox.replaceChildren() (Element)
Rebuild UIbox.replaceChildren(h2, p)
Check resultdoc.children.length / doc.documentElement
MDN statusBaseline Widely available (Oct 2020)

🔍 At a Glance

Four facts about document.replaceChildren().

Returns
undefined

MDN

Empty
()

no args

Args
nodes|strings

0+

Status
Baseline

Oct 2020

📋 replaceChildren vs append / prepend

MethodExisting childrenTypical use
replaceChildren(...)Removed, then new set insertedReset / swap entire child list
append(...)Kept; new nodes after last childAdd more at the end
prepend(...)Kept; new nodes before first childAdd more at the start
innerHTML = ""Clears (Element only; parses HTML)String-based clear / rebuild

Examples Gallery

Examples follow MDN Document: replaceChildren(). Labs use new Document() so they never wipe the live tutorial page.

📚 Getting Started

Empty a Document and install a new root safely in memory.

Example 1 — MDN: empty a Document

Call with no arguments; children becomes empty.

JavaScript
const doc = new Document();
const html = doc.createElement("html");
doc.append(html);

console.log("before:", doc.children.length); // 1

doc.replaceChildren();
console.log("after:", doc.children.length);  // 0
console.log(doc.children);                   // HTMLCollection []
Try It Yourself

How It Works

MDN’s empty pattern applied to an in-memory document — same API as document.replaceChildren() on any Document.

Example 2 — Replace with a new root <html>

Swap the document’s only element child in one call.

JavaScript
const doc = new Document();
const first = doc.createElement("html");
first.setAttribute("data-id", "first");
doc.append(first);

const second = doc.createElement("html");
second.setAttribute("data-id", "second");
doc.replaceChildren(second);

console.log(doc.documentElement.getAttribute("data-id")); // "second"
console.log(doc.children.length);                         // 1
Try It Yourself

How It Works

Old children are removed; the new node becomes the sole document element when the tree allows it.

📈 Practical Patterns

UI rebuilds on body, error handling, and comparison with append.

Example 3 — Everyday UI: body.replaceChildren()

Same method name on Element — the safe way to rebuild page content.

JavaScript
const title = document.createElement("h1");
title.textContent = "Hello again";
const note = document.createElement("p");
note.textContent = "Rebuilt with Element.replaceChildren";

// Prefer this over document.replaceChildren() on a live page
document.body.replaceChildren(title, note);

console.log(document.body.children.length); // 2
Try It Yourself

How It Works

Teach the Document API, then ship Element calls for real interfaces. See also Element.replaceChildren().

Example 4 — HierarchyRequestError on invalid trees

Two root elements are not allowed under an HTML Document.

JavaScript
const doc = new Document();
const a = doc.createElement("html");
const b = doc.createElement("html");

try {
  doc.replaceChildren(a, b); // invalid: two element children
} catch (err) {
  console.log(err.name); // "HierarchyRequestError"
}
Try It Yourself

How It Works

MDN: exceptions are thrown when node-tree constraints are violated. Wrap risky Document mutations in try/catch.

Example 5 — replaceChildren vs append

append keeps old children; replaceChildren resets them.

JavaScript
const docA = new Document();
docA.append(docA.createElement("html"));
// Cannot append a second html — would throw. Empty first:
docA.replaceChildren();
docA.append(docA.createElement("html"));
console.log("docA children:", docA.children.length); // 1

const box = document.createElement("div");
box.append(document.createElement("span"));
box.append(document.createElement("span"));
box.replaceChildren(document.createElement("strong"));
console.log("box children:", box.children.length);   // 1
Try It Yourself

How It Works

Use replace when you want a clean slate; use append/prepend when you want to keep existing siblings.

🚀 Common Use Cases

  • Empty an in-memory Documentdoc.replaceChildren() (MDN).
  • Swap a document root — replace with a new <html> or <svg> element.
  • Reset before rebuild — clear children, then append a valid root.
  • UI panels — use Element.replaceChildren() on containers (everyday).
  • Safer than innerHTML for nodes — pass real Node objects without string parsing.
  • Teaching ParentNode — same API on Document, Element, and DocumentFragment.

🧠 How replaceChildren() Works

1

You call replaceChildren

With zero or more nodes/strings (MDN).

Call
2

Old children are removed

The Document’s previous child list is cleared.

Clear
3

New set is inserted

Invalid trees throw HierarchyRequestError (MDN).

Insert
4

Children updated

Method returns undefined; inspect children / documentElement.

📝 Notes

  • MDN: Baseline Widely available since October 2020.
  • Not Deprecated, Experimental, or Non-standard.
  • Same ParentNode specification as Element.replaceChildren().
  • No-argument call empties the Document (MDN) — never do that on the live tutorial page.
  • For UI, prefer document.body.replaceChildren(...) or a container element.
  • Related: Document(), Element.replaceChildren(), Document.append(), Document.prepend().

Browser Support

Document.replaceChildren() is Baseline Widely available (MDN: across browsers since October 2020). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.replaceChildren()

ParentNode replaceChildren on Document — empty or swap document children; use Element.replaceChildren for UI.

Baseline Widely available
Google Chrome 86+
Yes
Microsoft Edge 86+
Yes
Mozilla Firefox 78+
Yes
Apple Safari 14+
Yes
Opera 72+
Yes
Internet Explorer No
No
replaceChildren() Widely available

Bottom line: Use document.replaceChildren() to empty or reset in-memory Documents. On loaded pages, prefer Element.replaceChildren() on body or a container.

Conclusion

document.replaceChildren() replaces or empties the Document’s children in one ParentNode call. Learn MDN’s empty pattern on new Document(), respect hierarchy rules, and use Element.replaceChildren() for everyday UI rebuilds.

Continue with requestStorageAccess(), Element.replaceChildren(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Practice empties on new Document() (MDN pattern)
  • Use Element.replaceChildren() for UI panels and lists
  • Pass real Node objects when you already have them
  • Catch HierarchyRequestError when experimenting with roots
  • Verify with children.length / documentElement

❌ Don’t

  • Call no-arg document.replaceChildren() on the live page
  • Assume two root elements are allowed under HTML Documents
  • Confuse Document and Element targets
  • Forget that the return value is undefined
  • Use Document.replaceChildren for every UI clear — prefer Element

Key Takeaways

Knowledge Unlocked

Five things to remember about replaceChildren()

Baseline ParentNode reset for Document children.

5
Core concepts
🗑02

Empty

no args

MDN
🎯03

UI

use Element

tip
⚠️04

Errors

Hierarchy*

MDN
🛡05

Status

Baseline

2020

❓ Frequently Asked Questions

MDN: Document.replaceChildren() replaces the existing children of a Document with a specified new set of children. With no arguments, the Document is emptied of all child nodes.
No. MDN marks Document.replaceChildren() as Baseline Widely available (across browsers since October 2020). It is not Deprecated, Experimental, or Non-standard.
MDN: call document.replaceChildren() with no arguments. Then document.children is an empty HTMLCollection.
Zero or more Node objects or strings (MDN). Strings become Text nodes. Invalid trees throw HierarchyRequestError.
Usually no for everyday UI. Emptying or replacing the live document root is destructive. Prefer Element.replaceChildren() on body or a container, or use replaceChildren on a new Document() when building documents in memory.
Same ParentNode API. Document.replaceChildren() targets the Document node itself; Element.replaceChildren() targets an element such as a div or body — the common choice for UI updates.
Did you know?

MDN’s Document page for replaceChildren() focuses on the empty call — the same ParentNode method powers Element and DocumentFragment, which is why UI tutorials almost always show el.replaceChildren() instead of the Document form.

Next: requestStorageAccess()

Learn how Document.requestStorageAccess() lets third-party embeds request unpartitioned cookie access.

requestStorageAccess() →

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.

6 people found this page helpful