JavaScript: Replace All Children, createDocumentFragment

By Xah Lee. Date: . Last updated: .

Here's the best way to replace all children of a element.

elem.innerHTML = "";
elem.appendChild( newDocFrag );

document.createDocumentFragment is similar to document.createElement, except that when you actually attach this element to DOM, the element itself disappears, only its children is attached.

document.createDocumentFragment is useful when you want to avoid the cost of browser rendering. For example, instead of attaching a list element li one by one for hundreds of them, you can attach them to a document fragment element, then attach the fragment to the live DOM.

Example:

"use strict";

// create a doc fragment
var ff = document.createDocumentFragment();

// create 5 p children and add it to the frag
for (var i = 0; i < 5; i++) {
    ff.appendChild(document.createElement("p"));
};

// frag has 5 children
console.log(ff.children.length); // 5

// create a div
var dd = document.createElement("div")

// append frag to div
dd.appendChild(ff);

// dd has 5 children, not 1. the frag dissapears
console.log(dd.children.length); // 5
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.