HTML DOM Document createDocumentFragment()

Examples

Add elements to an empty list:

const fruits = ["Banana", "Orange", "Mango"];

// Create a document fragment:
const dFrag = document.createDocumentFragment();

// Add li elements to the fragment:
for (let x in fruits) {
  const li = document.createElement('li');
  li.textContent = fruits[x];
  dFrag.appendChild(li);
}

// Add fragment to a list:
document.getElementById('myList').appendChild(dFrag);
Try it Yourself »

Add elements to an existing list:

const fruits = ["Banana", "Orange", "Mango"];

// Create a document fragment:
const dFrag = document.createDocumentFragment();

// Add li elements to the fragment:
for (let x in fruits) {
  const li = document.createElement('li');
  li.textContent = fruits[x];
  dFrag.appendChild(li);
}

// Add fragment to a list:
document.getElementById('myList').appendChild(dFrag);
Try it Yourself »

Description

The createDocumentFragment() method creates an offscreen node.

The offscreen node can be used to build a new document fragment that can be insert into any document.

The createDocumentFragment() method can also be used to extract parts of a document, change, add, or delete some of the content, and insert it back to the document.

Note

You can always edit HTML elements directly. But a better way is to construct an (offscreen) document fragment, and attach this fragment to the real (live) DOM when it is ready. Because you insert the fragment when it is ready, there will be only one reflow and one single render.

If you want to append HTML elements items in a loops, using document fragments also improves performance.

Warning!

Document nodes appended to the document fragment, are removed from the original document.


Syntax

document.createDocumentFragment()

Parameters

NONE

Return Value

Type Description
NodeThe created DocumentFragment node.

Browser Support

document.createComment() is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.