liveBook · Manning

DOM fragment

As explained in Secrets of the JavaScript Ninja, Second Edition

A lightweight, detached portion of a DOM tree that can be manipulated separately before being inserted into a document.

When a page needs to add generated HTML in several places, inserting nodes one by one can mean extra DOM operations. A DOM fragment is a container for a collection of nodes: build the nodes into it, then insert or clone the fragment as a unit. section 12.1 section 12.1.2

A fragment fits into a simple workflow:

  • Convert the HTML string into DOM nodes, then add those nodes to a fragment. section 12.1.2
  • Insert the fragment in one operation. For multiple destinations, clone the fragment for later insertions instead of cloning each node individually. section 12.1.2

One fragment, multiple destinations

Create a fragment with document.createDocumentFragment(), pass it to the HTML-to-nodes helper, then insert the fragment into the first target and a clone into each additional target. section 12.1.2

Listing 12.4. Inserting a DOM fragment into multiple locations in the DOM
<div id="test"><b>Hello</b>, I'm a ninja!</div>                 #A
<div id="test2"></div>                                          #A
<script>
  document.addEventListener("DOMContentLoaded", () => {
    function insert(elems, args, callback) {
      if (elems.length) {
        const doc = elems[0].ownerDocument || elems[0],
              fragment = doc.createDocumentFragment(),          #B
              scripts = getNodes(args, doc, fragment),          #C
              first = fragment.firstChild;
        if (first) {
          for (let i = 0; elems[i]; i++) {
            callback.call(root(elems[i], first),
                i > 0 ? fragment.cloneNode(true) : fragment);   #D
          }
        }
      }
    }
    const divs = document.querySelectorAll("div");
    insert(divs, "<b>Name:</b>", function (fragment) {
      this.appendChild(fragment);
    });

    insert(divs, "<span>First</span> <span>Last</span>",
        function (fragment) {
          this.parentNode.insertBefore(fragment, this);
        });
  });
</script>

See the insertion pattern applied to multiple elements, including cloning the fragment for later targets. section 12.1.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines fragments as node containers and demonstrates adding, inserting, and cloning them.
Examples
Demonstrates building nodes from an HTML string and inserting a fragment into multiple document locations.
What you can do after
Apply it via document.createDocumentFragment() to batch node insertion and clone content for additional targets.
How it connects
Connects DOM fragments with DOM nodes, HTML-string parsing, cloning, and document insertion.

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 Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.