Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

document.createDocumentFragment() — creating a DOM fragment

document.createDocumentFragment() creates an empty DOM fragment. You can collect nodes in it and then move them into a parent without adding an extra wrapper element.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const fragment = document.createDocumentFragment();

document.createDocumentFragment() takes no arguments and returns a new, empty DocumentFragment associated with the calling document. It is a DOM node, not an element; it serves as a temporary container for other nodes.

With target.appendChild(fragment), the fragment's children enter target in their existing order, not the fragment itself. Nodes are moved, not copied, so they retain their identity. The fragment becomes empty and can be reused. appendChild() returns the supplied fragment, not its children.

The example uses a detached target, so it does not change the visible page. Run it in a browser with document available; a JavaScript runtime alone does not guarantee this API.

Examples

{
  const fragment = document.createDocumentFragment();
  const target = document.createElement('ul');

  for (const label of ['A', 'B']) {
    const item = document.createElement('li');
    item.textContent = label;
    fragment.appendChild(item);
  }

  const first = fragment.firstChild;
  const returned = target.appendChild(fragment);

  console.log(target.textContent);
  console.log(target.childNodes.length);
  console.log(fragment.childNodes.length);
  console.log(target.firstChild === first);
  console.log(returned === fragment);
}

Result

AB
2
0
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources