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.


"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++) {

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

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

// append frag to div

// 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.