JavaScript Document createDocumentFragment() Method

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

What You’ll Learn

document.createDocumentFragment() is an instance method that returns an empty DocumentFragment — a lightweight, offscreen container for building DOM subtrees (see MDN Document: createDocumentFragment()). Learn batch insertion, why the fragment disappears after appendChild, the MDN browser-list example, and new DocumentFragment() as an alternative — with five try-it labs.

01

Kind

Instance method

02

Args

None

03

Returns

DocumentFragment

04

In DOM?

Offscreen

05

On insert

Children move

06

Status

Baseline

Introduction

When you need to add many nodes to the page, appending each one directly to a live container can trigger repeated layout work. A common pattern is:

  1. Create a DocumentFragment with createDocumentFragment().
  2. Build your elements on the fragment (offscreen).
  3. Append the fragment to the live DOM once.

MDN: DocumentFragments are DOM node objects which are never part of the main DOM tree. When you append the fragment, it is replaced by all its children.

💡
The fragment is a temporary staging area

Think of it like a clipboard for DOM nodes. After insertion, the fragment itself is empty — its child nodes become direct children of the target parent.

Related tutorials: append(), nodeType, createComment().

Understanding document.createDocumentFragment()

An instance method on any Document object, including the live page document (MDN).

  • Parameters — none (MDN).
  • Return value — a new, empty DocumentFragment (MDN).
  • nodeTypeNode.DOCUMENT_FRAGMENT_NODE (11).
  • nodeName"#document-fragment".
  • Not in main tree — lives in memory until inserted (MDN).
  • On append — fragment replaced by its children (MDN).

📝 Syntax

General form of Document.createDocumentFragment (MDN):

JavaScript
createDocumentFragment()

Parameters

None.

Return value

A newly created, empty, DocumentFragment object (MDN).

Alternative constructor (MDN)

JavaScript
const fragment = new DocumentFragment();

MDN browser list example

JavaScript
const element = document.getElementById("ul");
const fragment = document.createDocumentFragment();
const browsers = ["Firefox", "Chrome", "Opera", "Safari"];

browsers.forEach((browser) => {
  const li = document.createElement("li");
  li.textContent = browser;
  fragment.appendChild(li);
});

element.appendChild(fragment);

⚡ Quick Reference

GoalCode
Create fragmentdocument.createDocumentFragment()
Add childfragment.appendChild(node)
Insert into DOMparent.appendChild(fragment)
nodeTypeNode.DOCUMENT_FRAGMENT_NODE (11)
After insertfragment.childNodes.length === 0
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createDocumentFragment().

Returns
DocumentFragment

empty container

Args
none

no parameters

Type
11

FRAGMENT_NODE

Insert
children move

not a wrapper

📋 Direct append vs DocumentFragment

PatternDOM updatesWhen to prefer
Append each node to live parentOne per nodeAdding 1–2 nodes
Build on fragment, append onceOne batchLists, tables, many siblings
DocumentFragment constructorSame as methodWhen you skip document
parent.replaceChildren(...)One replaceReplace all children at once

Examples Gallery

Examples follow MDN Document: createDocumentFragment() and show batch DOM building patterns.

📚 Getting Started

Create fragments and insert built subtrees.

Example 1 — MDN: browser list with forEach

Official MDN example — build <li> nodes offscreen, then insert.

JavaScript
const element = document.getElementById("ul");
const fragment = document.createDocumentFragment();
const browsers = ["Firefox", "Chrome", "Opera", "Safari"];

browsers.forEach((browser) => {
  const li = document.createElement("li");
  li.textContent = browser;
  fragment.appendChild(li);
});

element.appendChild(fragment);
Try It Yourself

How It Works

All four list items are built on the fragment, then moved into #ul in one append.

Example 2 — Batch table rows into <tbody>

Build multiple <tr> elements before touching the live table.

JavaScript
const tbody = document.querySelector("#data tbody");
const fragment = document.createDocumentFragment();
const rows = [
  ["Alice", "42"],
  ["Bob", "37"]
];

rows.forEach(([name, score]) => {
  const tr = document.createElement("tr");
  tr.innerHTML = `<td>${name}</td><td>${score}</td>`;
  fragment.appendChild(tr);
});

tbody.appendChild(fragment);
console.log(tbody.rows.length); // 2
Try It Yourself

How It Works

Same batch pattern as the MDN list — useful for dynamic tables and grids.

📈 Practical Patterns

Node inspection and fragment lifecycle.

Example 3 — nodeType is DOCUMENT_FRAGMENT_NODE (11)

Identify fragment nodes before insertion.

JavaScript
const fragment = document.createDocumentFragment();

console.log(fragment.nodeType === Node.DOCUMENT_FRAGMENT_NODE); // true
console.log(fragment.nodeName); // "#document-fragment"
console.log(fragment.childNodes.length); // 0
Try It Yourself

How It Works

Fragments are a distinct node type, separate from elements and text nodes.

Example 4 — Fragment is empty after append (MDN)

MDN: the fragment is replaced by its children in the DOM tree.

JavaScript
const host = document.getElementById("host");
const fragment = document.createDocumentFragment();

fragment.appendChild(document.createElement("p"));
fragment.appendChild(document.createElement("p"));

console.log("before:", fragment.childNodes.length); // 2

host.appendChild(fragment);

console.log("after:", fragment.childNodes.length); // 0
console.log("host children:", host.childNodes.length); // 2
Try It Yourself

How It Works

Child nodes move out of the fragment; the fragment does not remain as a wrapper element.

Example 5 — new DocumentFragment() alternative (MDN)

MDN documents the constructor as an equivalent way to create a fragment.

JavaScript
const viaMethod = document.createDocumentFragment();
const viaConstructor = new DocumentFragment();

viaMethod.append(document.createElement("span"));
viaConstructor.append(document.createElement("span"));

console.log(viaMethod.childNodes.length); // 1
console.log(viaConstructor.childNodes.length); // 1
console.log(viaMethod.nodeType === viaConstructor.nodeType); // true
Try It Yourself

How It Works

Both produce empty fragments with the same node type. Pick the style that fits your codebase.

🚀 Common Use Cases

  • Dynamic lists — MDN browser list pattern with many <li> items.
  • Table bodies — batch-build <tr> rows before inserting.
  • Virtual scrolling prep — assemble a chunk of nodes offscreen.
  • Template rendering — build a subtree, then attach once.
  • Performance — MDN: can help in older engines by reducing reflows.
  • Not a visible element — fragments never render; only their children do.

🧠 How createDocumentFragment() Works

1

Call with no arguments

MDN: returns an empty DocumentFragment.

Create
2

Append nodes to fragment

Use appendChild, append, or prepend on the fragment.

Build
3

Insert fragment into live DOM

parent.appendChild(fragment) or append.

Attach
4

Children move; fragment empties

MDN: fragment replaced by all its children in the parent.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • No parameters — always returns an empty fragment.
  • Fragments are offscreen; not part of the main DOM tree while building (MDN).
  • After insertion, fragment.childNodes is typically empty.
  • nodeType is 11 (DOCUMENT_FRAGMENT_NODE).
  • Related: append(), nodeType, createComment().

Browser Support

Document.createDocumentFragment() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.createDocumentFragment()

Creates DocumentFragment nodes — supported across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createDocumentFragment() Wide

Bottom line: Fully supported for batch DOM building. Prefer fragments when inserting many sibling nodes at once.

Conclusion

document.createDocumentFragment() returns an empty offscreen container for building DOM subtrees. Append your elements to the fragment, then insert it once — MDN: the fragment is replaced by all its children. Use it for lists, tables, and any batch DOM work where a single insertion beats many.

Continue with createElement(), append(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use fragments when inserting many sibling nodes
  • Build offscreen, then append the fragment once
  • Reuse the same pattern as MDN’s browser list example
  • Check nodeType === Node.DOCUMENT_FRAGMENT_NODE when debugging
  • Consider new DocumentFragment() if you prefer constructors

❌ Don’t

  • Expect the fragment to stay as a wrapper in the DOM
  • Assume children remain on the fragment after append
  • Use fragments for a single node (just append the element)
  • Confuse with createComment (comment nodes)
  • Rely on fragments alone for XSS-safe HTML parsing

Key Takeaways

Knowledge Unlocked

Five things to remember about createDocumentFragment()

Offscreen batch container for DOM nodes.

5
Core concepts
📄02

Args

none

MDN
03

Insert

children move

key rule
📈04

Type

11

FRAGMENT
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createDocumentFragment() creates a new empty DocumentFragment — an offscreen container for DOM nodes. Build children on the fragment, then insert the fragment into the live tree in one step.
No. MDN marks Document.createDocumentFragment() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A new, empty DocumentFragment object ready for nodes to be inserted into it (MDN). It has no parameters.
MDN: In the DOM tree, the document fragment is replaced by all its children. The fragment itself is not left as a wrapper — its child nodes move to the parent.
Both create an empty fragment. MDN notes you can also use the DocumentFragment constructor. createDocumentFragment() is the classic Document instance method and works everywhere the API is supported.
MDN: Fragments are never part of the main DOM tree while you build them. Batch-building offscreen can reduce reflows when inserting many nodes at once — especially helpful in older engines.
Did you know?

After you append a DocumentFragment, you can reuse the same variable to build another batch — MDN’s usage notes explain that the fragment empties when its children move. Many libraries use this pattern internally for efficient list rendering.

Next: createElement()

Learn how to create HTML element nodes and insert them into the DOM.

createElement() →

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