Chapter 9: DOM element Methods

9.2 Document Fragments

In the previous section, we learned to use various built-in Javascript methods like createElement() and insertBefore() to add nodes to our HTML page directly.

While it is very easy to do so, there is one slight problem – adding nodes to our HTML page directly requires the browser to re-render the HTML page every time we modify it. This involves recalculating the layout, CSS styles etc, which is a very inefficient way of doing things.

Instead of adding nodes to the HTML page directly, a better way is to use document fragments.

Here’s how it works.

Suppose we want to add five <p> elements to NodesPractice.html. We’ll create a document fragment and add the elements to it first. Only after we’ve added all the elements to the document fragment, will we append the document fragment to the HTML document. When we do it this way, the HTML document only needs to be re-rendered once, instead of 5 times. An example is shown below:

var docFrag = document.createDocumentFragment();
var paraToAdd;
var textContent;

for (i = 1; i<=5; ++i) {
    paraToAdd = document.createElement("p");
    textContent = document.createTextNode("Paragraph " + i + " Added"); 
    paraToAdd.appendChild(textContent);

    docFrag.appendChild(paraToAdd);
}

document.querySelector("#original").appendChild(docFrag);

In the code above, we use the built-in createDocumentFragment() method to create a new document fragment and assign it to a variable called docFrag.

We also declare two variables called paraToAdd and textContent.

Next, we use a for loop to add five <p> elements to our document fragment. Within the for loop, the first three statements should be familiar to you. What is new is the last statement.

Here, instead of appending the element/text node pair to the HTML document directly, we append it to the document fragment.

After the for loop completes, we finally append the document fragment to the actual HTML document (on line 13).

If you add the code to chap9.js and refresh NodesPractice.html now, you’ll get

Javascript Document Fragment
as the output.