What is DocumentFragment and createDocumentFragment() in JavaScript

document fragment
Image by Martina Bulková from Pixabay

What is DocumentFragment?

DocumentFragment is a JavaScript interface that represents a minimal document object which has no parent. It stores a part of a document structure comprised of nodes just like a standard document. DocumentFragment is not the part of active DOM tree.

As it’s an ‘out-of-dom’ element, the changes you make to it does not affect the actual DOM tree, thus improving the performance. To create the DocumentFragment we use createDocumentFragment() method.

Let’s see it in detail.

createDocumentFragment() Method

This method creates an offscreen node. Here, offscreen means that the node is not actually added to the DOM until it is appended to the existing DOM element. This method will return a newly created document fragment node that can be used to delete, modify and add a new node without affecting the existing DOM tree.

 let fragmentObject = document.createDocumentFragment();

As you can see in the above syntax, this method does not take any parameters. Below is the example which demonstrates it in practice.

HTML

<ul id="listElement">
</ul>

JavaScript

let element  = document.getElementById('listElement'); // existing ul element
let fragmentObject = document.createDocumentFragment();
let coding = ['PHP','Java','C'];

coding.forEach(function(code) {
    let li = document.createElement('li');
    li.textContent = code;
    fragmentObject.appendChild(li);
});

element.appendChild(fragmentObject);

Output

  • PHP
  • Java
  • C

As you can see in the above example, first we composed DOM nodes before updating them to the active DOM tree to get better performance.

The difference between createElement and createDocumentFragment is that,

When you create an element with createElement and append it to the DOM, the element is appended to the DOM, as well as the children.

With a createDocumentFragment, only the children are appended. Since the document fragment is in memory and not part of the live DOM tree, appending children to it does not cause page reflow.

Leave a Reply

Your email address will not be published. Required fields are marked *