JavaScript Reference ยท DOM: Document and Elements
The DocumentFragment interface
Reference for DocumentFragment: a lightweight container that holds nodes off-page so you can build several elements and insert them into the DOM in one step.
A DocumentFragment is a minimal node that has children but is not part of any page. You create one, add elements to it, and then insert the fragment into the document. When you do, the fragment's children move into place and the fragment itself is left empty; the fragment never appears in the tree.
That makes it a neat way to prepare a group of nodes as a single unit, and to insert them with one DOM operation instead of many.
const fragment = document.createDocumentFragment(); // or: new DocumentFragment()
Try it
Syntax
new DocumentFragment() document.createDocumentFragment()
Useful members
| Name | Description |
|---|---|
append(...nodes) / prepend(...nodes) |
Add nodes or strings to the fragment. |
appendChild(node) / insertBefore(node, ref) |
Classic insertion methods, available on every node. |
querySelector() / querySelectorAll() |
Search inside the fragment. |
getElementById(id) |
Finds an element by id inside the fragment. |
children, childNodes, firstElementChild |
Read the fragment's contents. |
replaceChildren(...nodes) |
Replace all children. |
cloneNode(true) |
Make a deep copy; the copy is another fragment. |
Return value
Both constructors return a new, empty DocumentFragment.
Usage notes
- Insertion moves the children. After
parent.append(fragment)the fragment is empty. If you need to insert the same structure twice, callcloneNode(true)on the fragment first. - Is it faster? Rarely by much. Browsers do not re-render after every DOM change; they batch layout work until the script yields. A fragment mainly keeps your code tidy and gives one insertion point. Building a long HTML string and setting
innerHTMLonce is also fast; measure before optimizing. - A fragment has no parent, styles or layout. Elements inside it are not matched by page CSS and
getBoundingClientRect()returns zeros until they are inserted. - Fragments from
<template>. Thecontentof a<template>is aDocumentFragment; see the template element. - Fragments are not elements. They have no
innerHTML,classListorid, and cannot be inserted into a page "as themselves", only through their children. - Shadow roots are fragments too.
ShadowRootinherits fromDocumentFragment, which is why many of the same methods work on it. - Event listeners attached to children are kept. Moving nodes does not remove their listeners, unlike serializing and re-parsing HTML.
Browser support
createDocumentFragment() has worked in every browser for a very long time. The new DocumentFragment() constructor and methods such as append() and replaceChildren() are supported in all current browsers.