JS: Replace All Children, createDocumentFragment

By Xah Lee. Date: . Last updated: .

Here is 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:

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

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

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

// create a div
const 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
BUY Ξ£JS JavaScript in Depth