Chapter 8. DocumentFragment Nodes

8.1 DocumentFragment Object Overview

The creation and use of a DocumentFragment node provides a lightweight document DOM that is external to the live DOM tree. Think of a DocumentFragment as an empty document template that acts just like the live DOM tree, but only lives in memory, and its child nodes can easily be manipulated in memory and then appended to the live DOM.

8.2 Using createDocumentFragment() to Create DocumentFragments

In the following code, a DocumentFragment is created by using createDocumentFragment(), and <li>s are appended to the fragment.

Live code

<!DOCTYPE html>
<html lang="en">
<body>

<script>

var docFrag = document.createDocumentFragment();

["blue", "green", "red", "blue", "pink"].forEach(function(e) {
    var li = document.createElement("li");
    li.textContent = e;
    docFrag.appendChild(li);
});

console.log(docFrag.textContent); //logs bluegreenredbluepink

</script>
</body>
</html>

Using a document fragment to create node structures in memory is extremely efficient when it comes time to inject the document fragment into live node structures.

You might wonder what is the advantage to using a document fragment over simply creating (via createElement()) a <div> in memory and working within this <div> to create a DOM structure. Here are the differences between the two:

  • A document fragment may contain any kind of node (except <body> or <html>), whereas an element may not.

  • The document fragment itself is not added to the DOM when you append a ...

Get DOM Enlightenment now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.