Document

document.createDocumentFragment

Creates a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree

Syntax

JavaScript
document.createDocumentFragment()

Return Value

A newly created empty DocumentFragment

Examples

Basic Usage
const frag = document.createDocumentFragment()
for (let i = 0; i < 5; i++) {
  const li = document.createElement('li')
  li.textContent = `Item ${i}`
  frag.appendChild(li)
}
document.querySelector('ul')?.appendChild(frag)
Practical Example
function renderList(items: string[]) {
  const frag = document.createDocumentFragment()
  items.forEach(item => {
    const div = document.createElement('div')
    div.textContent = item
    frag.appendChild(div)
  })
  return frag
}
Advanced Usage
const fragment = document.createDocumentFragment()
const header = document.createElement('h2')
header.textContent = 'Title'
fragment.appendChild(header)
fragment.appendChild(document.createElement('hr'))
document.getElementById('content')?.appendChild(fragment)

Understanding document.createDocumentFragment

The document.createDocumentFragment method in JavaScript creates a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree. It belongs to the Document object and is one of the most widely used methods for working with document values in modern JavaScript and TypeScript applications.

The method signature is document.createDocumentFragment(). When called, it returns a newly created empty documentfragment. Understanding when and how to use createDocumentFragment() helps you write more expressive, readable code.

Common use cases for document.createDocumentFragment include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-createelement, dom-appendchild, dom-append, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for document.createDocumentFragment is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Document Methods

Other methods in the Document object

Related Tools

More Document Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.