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

