liveBook · Manning

DOM fragment

As explained in Web Components in Action

A document fragment is a lightweight DOM node that can contain a subtree of nodes without itself being part of a document tree.

A document fragment is a lightweight, separate DOM tree that can hold nodes without rendering as part of the page. It provides a temporary place to assemble content before inserting that content into the document. section 7.2 section 8.2

Use a fragment when you want to build several nodes before adding them to the page:

  • Create one with document.createDocumentFragment(). section 7.2
  • Append newly created elements to the fragment while constructing the subtree. section 7.2
  • Append the fragment to the document once, avoiding repeated direct insertions and their associated DOM recalculation. section 7.2
  • Expect its child nodes to move into the document, leaving the fragment itself without those children. section 7.2

Adding five paragraphs

Create a fragment, loop five times to make paragraph elements, append each paragraph to the fragment, and then call document.body.appendChild(fragment). The page receives five sibling paragraphs rather than an extra wrapper element. section 7.2

Listing 7.4. Using a document fragment
<html>
<head>
   <title>Document Fragment Demo</title>
</head>
<body>
<script>
   const fragment =                                #1
       document.createDocumentFragment();
   for (let c = 0; c < 5; c++) {
       const li = document.createElement('p');
       li.innerText = 'paragraph ' + c;
       fragment.appendChild(li);                   #2
   }
   document.body.appendChild(fragment);            #3
</script>
</body>
</html>

Inspect the complete fragment example, including node creation, repeated fragment appends, and the final document insertion. section 7.2

How Web Components in Action covers it

How deep it goes
Explains construction, child movement, and insertion performance, but stops short of broader DOM implementation internals.
Examples
Demonstrates five generated paragraphs, template content cloning, and inspection of shadow roots in browser developer tools.
What it assumes
Assumes basic HTML and JavaScript DOM familiarity while introducing fragment behavior through progressively explained examples.
What you can do after
Apply it via JavaScript DOM APIs to build node groups and insert them into a document with one append operation.
How it connects
Connects document fragments to the template element, DOM trees, Shadow DOM, shadow roots, and Web Components.

Also explained in

Compare how 2 books explain DOM fragment →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.