Skip to content

24 ways to impress your friends

Vote down?

Jason Hummel

If you’d rather not play around with all that messy string concatenation when performing costly DOM manipulations, give createDocumentFragment a try.

var div = document.createElement(“div”);
div.appendChild( document.createTextNode(“Test div to be inserted 100 times”) );

var fragment = document.createDocumentFragment();

for(i = 0; i < 100; i++) { fragment.appendChild( div.cloneNode(true) );
}

document.getElementById(“container”).appendChild( fragment.cloneNode(true)
);

Amazingly the browser support for documentFragments goes back to IE6.The benefit comes from the ability to add the entire fragment DOM tree into the page DOM with one insertion – just like the method outlined in the article.