Table of Contents

Introduction

JavaScript DocumentFragment is a lightweight container used to hold DOM nodes without immediately adding them to the document. It allows developers to create and organize multiple HTML elements before inserting them into the DOM.

When you need to add several elements dynamically, inserting each element separately can cause unnecessary DOM updates. A DocumentFragment helps you prepare all the elements first and then append them to the document in a single operation.

In this tutorial, you will learn how DocumentFragment works, how to create one, how to append elements, and how to use it with practical JavaScript examples.

What Is DocumentFragment in JavaScript?

A DocumentFragment is a minimal document object that does not have a parent node. It can contain multiple DOM nodes, such as HTML elements and text nodes.

Unlike a regular HTML element, a DocumentFragment is not displayed on the webpage. It acts as a temporary container for DOM elements.

You can create a DocumentFragment using the document.createDocumentFragment() method.

Syntax

const fragment = document.createDocumentFragment();

The returned object can hold multiple nodes. When you append the fragment to an element, its child nodes are moved into that element.

Creating a DocumentFragment

The createDocumentFragment() method creates an empty DocumentFragment object.

Example

<div id="container"></div>

<script>
const fragment = document.createDocumentFragment();

console.log(fragment);
console.log(fragment.nodeType);
</script>

Output:

#document-fragment
11

The nodeType property returns 11, which represents a DocumentFragment node.

Adding HTML Elements to a DocumentFragment

You can create HTML elements with document.createElement() and append them to a DocumentFragment.

Example

<div id="container"></div>

<script>
const fragment = document.createDocumentFragment();

const heading = document.createElement("h2");
heading.textContent = "JavaScript DocumentFragment";

const paragraph = document.createElement("p");
paragraph.textContent = "DocumentFragment helps organize DOM nodes.";

fragment.appendChild(heading);
fragment.appendChild(paragraph);

document.getElementById("container").appendChild(fragment);
</script>

Output:

<div id="container">
    <h2>JavaScript DocumentFragment</h2>
    <p>DocumentFragment helps organize DOM nodes.</p>
</div>

Both elements are prepared inside the fragment before being inserted into the container.

Using DocumentFragment with a Loop

DocumentFragment is particularly useful when generating multiple elements dynamically.

Example

<ul id="languageList"></ul>

<script>
const languages = ["JavaScript", "Python", "PHP", "Java"];

const fragment = document.createDocumentFragment();

languages.forEach(function(language) {
    const li = document.createElement("li");
    li.textContent = language;

    fragment.appendChild(li);
});

document.getElementById("languageList").appendChild(fragment);
</script>

Output:

  • JavaScript
  • Python
  • PHP
  • Java

The loop creates each list item and stores it in the fragment. After the loop finishes, the fragment is appended to the list.

DocumentFragment appendChild() Method

The appendChild() method adds a node to the end of a DocumentFragment.

Syntax

fragment.appendChild(node);

Here, fragment is the DocumentFragment object and node is the element or node you want to add.

Example

const fragment = document.createDocumentFragment();

const first = document.createElement("p");
first.textContent = "First paragraph";

const second = document.createElement("p");
second.textContent = "Second paragraph";

fragment.appendChild(first);
fragment.appendChild(second);

console.log(fragment.childNodes.length);

Output:

2

The fragment contains two child nodes before it is inserted into the document.

DocumentFragment append() Method

The append() method allows you to append multiple nodes or strings to a DocumentFragment.

Example

const fragment = document.createDocumentFragment();

const heading = document.createElement("h2");
heading.textContent = "DOM Manipulation";

const paragraph = document.createElement("p");
paragraph.textContent = "Learn JavaScript DOM methods.";

fragment.append(heading, paragraph, " Tutorial");

document.getElementById("container").appendChild(fragment);

Unlike appendChild(), the append() method can accept multiple arguments and string values.

Moving Elements from DocumentFragment to the DOM

When a DocumentFragment is appended to an element, its child nodes are moved into the target element. The fragment itself is not inserted.

Example

<div id="output"></div>

<script>
const fragment = document.createDocumentFragment();

const message = document.createElement("p");
message.textContent = "Hello from DocumentFragment!";

fragment.appendChild(message);

const output = document.getElementById("output");
output.appendChild(fragment);

console.log(fragment.childNodes.length);
console.log(output.textContent);
</script>

Output:

0
Hello from DocumentFragment!

After insertion, the fragment becomes empty because its child nodes have been transferred to the target element.

DocumentFragment vs Regular DOM Element

A DocumentFragment and a regular HTML element can both contain child nodes, but they serve different purposes.

Feature DocumentFragment Regular DOM Element
Appears on webpage No Yes
Has a parent node No Usually yes
Can contain child nodes Yes Yes
Can be appended to DOM Yes Yes
Remains after insertion No, its children move Yes
Main purpose Temporary node container HTML structure

A DocumentFragment is useful as a temporary container, while a regular DOM element represents part of the actual webpage.

Accessing DocumentFragment Child Nodes

You can use properties such as children, childNodes, and firstChild to access nodes inside a DocumentFragment.

Example

const fragment = document.createDocumentFragment();

const heading = document.createElement("h2");
heading.textContent = "JavaScript";

const paragraph = document.createElement("p");
paragraph.textContent = "DocumentFragment example";

fragment.append(heading, paragraph);

console.log(fragment.children.length);
console.log(fragment.firstChild.textContent);
console.log(fragment.lastChild.textContent);

Output:

2
JavaScript
DocumentFragment example

The children property returns element nodes, while childNodes also includes text nodes and other node types.

Using DocumentFragment with replaceChildren()

The replaceChildren() method replaces the existing children of an element with the nodes or strings you provide. You can pass a DocumentFragment to insert multiple prepared nodes.

Example

<div id="content">
    <p>Old content</p>
</div>

<script>
const fragment = document.createDocumentFragment();

const heading = document.createElement("h2");
heading.textContent = "Updated Content";

const paragraph = document.createElement("p");
paragraph.textContent = "Content created with DocumentFragment.";

fragment.append(heading, paragraph);

document.getElementById("content").replaceChildren(fragment);
</script>

The existing paragraph is replaced by the heading and the new paragraph.

Performance Considerations of DocumentFragment

DocumentFragment can make DOM manipulation code cleaner by allowing multiple nodes to be prepared before insertion.

Instead of appending every newly created node directly to the document, you can append the nodes to a fragment and then insert the fragment.

However, modern browsers optimize DOM operations, so DocumentFragment does not guarantee a measurable performance improvement in every situation. Its main advantage is convenient and organized DOM construction.

Common Mistakes When Using DocumentFragment

1. Expecting the Fragment to Remain in the DOM

A DocumentFragment is not inserted as a visible element. Its children are moved into the destination element.

2. Trying to Display the Fragment Directly

A fragment is only a temporary container. Append it to an actual DOM element to display its child nodes.

3. Accessing the Fragment After Insertion

After appending the fragment, its child nodes have moved to the destination. Therefore, its childNodes.length will normally be 0.

4. Confusing children and childNodes

The children property returns only element nodes. The childNodes property can also include text nodes and comments.

Combining DocumentFragment with DOM Methods

DocumentFragment works with other JavaScript DOM methods, including createElement(), appendChild(), append(), and replaceChildren().

Complete Example

<ul id="studentList"></ul>

<script>
const students = [
    "Rahim",
    "Karim",
    "Nadia",
    "Sadia"
];

const studentList = document.getElementById("studentList");
const fragment = document.createDocumentFragment();

students.forEach(function(student) {
    const listItem = document.createElement("li");

    listItem.textContent = student;
    fragment.appendChild(listItem);
});

studentList.appendChild(fragment);
</script>

This example creates a list of students dynamically and inserts all list items into the webpage using a DocumentFragment.

Categorized in:

Javascript, Js DOM,