liveBook · Manning

DOM fragment

As explained in Vanilla Web

A lightweight DOM container that holds a subtree of nodes without being part of the document tree itself.

When an update needs several nodes, a DOM fragment provides a lightweight container for assembling them outside the page’s live tree. Add the finished nodes to the page together instead of inserting each one as it is created. section 6.2.9

Build a list before attaching it

Create a fragment with document.createDocumentFragment(). For each item, create an li with document.createElement('li'), set its textContent, and append it to the fragment. Finally, call list.append(fragment). The list receives the children; the fragment does not become a wrapper around them. section 6.2.9 section 8.1.2

An HTML template uses a fragment differently: template.content holds parsed markup that is not rendered or run while it remains in the template. This makes a template useful for reusable rows, cards, and component markup without a hidden wrapper or an HTML string assembled in JavaScript. A fragment used as a construction buffer is not, by itself, a reusable blueprint. section 8.1 section 8.1.2

Keep the fragment’s ownership and one-time insertion behavior in mind:

  • Appending a fragment moves its children into the destination and leaves the fragment empty. For repeated UI, insert a deep copy from template.content.cloneNode(true), or use document.importNode(template.content, true). section 8.1.2
  • Attach event listeners to the inserted copies, not to template.content. Cloning creates new nodes and does not copy listeners registered with addEventListener. section 8.1.2
  • For nodes originating in another document, account for document ownership: adoptNode transfers a node, while importNode clones it into the destination document. section 6.2.3

How Vanilla Web covers it

How deep it goes
Explains child transfer, template ownership, deep cloning, importing, and listener caveats without detailing browser internals.
Examples
Uses repeated table rows, cards, tooltips, and component markup as template candidates, alongside buffered multi-node insertion.
What it assumes
Introduces fragments alongside element creation; expects familiarity with basic DOM insertion when discussing template cloning.
What you can do after
Build it from scratch with native DOM creation APIs, or clone template content before inserting reusable nodes.
How it connects
Connects HTML templates and DOM insertion with cloneNode, importNode, adoptNode, and document ownership.

Also explained in

Compare how 3 books explain DOM fragment →

Related concepts

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