Should I use document.createDocumentFragment or document.createElement

Asked
Active3 hr before
Viewed126 times

7 Answers

90%

I was reading about document fragments and DOM reflow and wondered how document.createDocumentFragment differed from document.createElement as it looks like neither of them exist in the DOM until I append them to a DOM element.,When you create an element and append it to the DOM, the element is appended to the DOM, as well as the children.,I did a test (below) and all of them took exactly the same amount of time (about 95ms). At a guess this could possibly be due to there being no style applied to any of the elements, so no reflow maybe. ,Anyway, based on the example below, why should I use createDocumentFragment instead of createElement when inserting into the DOM and whats the differnce between the two.

This allows you to insert multiple nodes into the DOM at the same time:

var frag = document.createDocumentFragment();
var textNode = frag.appendChild(document.createTextNode("Some text"));
var br = frag.appendChild(document.createElement("br"));
var body = document.body;
body.appendChild(frag);
alert(body.lastChild.tagName); // "BR"
alert(body.lastChild.previousSibling.data); // "Some text"
alert(frag.hasChildNodes()); // false
load more v
88%

Creates a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree. , A newly created, empty, DocumentFragment object, which is ready to have nodes inserted into it. ,createDocumentFragment(), You can also use the DocumentFragment constructor to create a new fragment:

var fragment = document.createDocumentFragment();
load more v
72%

I was reading about document fragments and DOM reflow and wondered how document.createDocumentFragment differed from document.createElement as it looks like neither of them exist in the DOM until I append them to a DOM element.,Another very important difference between creating an element and a document fragment:,With a document fragment, only the children are appended.,Anyway, based on the example below, why should I use createDocumentFragment instead of createElement when inserting into the DOM and whats the differnce between the two.

Anyway, based on the example below, why should I use createDocumentFragment instead of createElement when inserting into the DOM and whats the differnce between the two.

var htmz = "<ul>";
for (var i = 0; i < 2001; i++) {
    htmz += '<li><a href="#">link ' + i + '</a></li>';
}
htmz += '<ul>';

//createDocumentFragment
console.time('first');
var div = document.createElement("div");
div.innerHTML = htmz;
var fragment = document.createDocumentFragment();
while (div.firstChild) {
    fragment.appendChild(div.firstChild);
}
$('#first').append(fragment);
console.timeEnd('first');

//createElement
console.time('second');
var span = document.createElement("span");
span.innerHTML = htmz;
$('#second').append(span);
console.timeEnd('second');


//jQuery
console.time('third');
$('#third').append(htmz);
console.timeEnd('third');
load more v
65%

TL;DR: Use DocumentFragments. http://jsperf.com/document-fragment-vs-innerhtml-vs-looped-appendchild,Instead of appending the elements directly to the document when they are created, append them to the DocumentFragment instead, and finish by adding that to the DOM.,If you ever find yourself appending a series of elements to the DOM, you should always use a DocumentFragment to do just that. ,Why? Not only is using DocumentFragments to append about 2700 times faster than appending with innerHTML, but it also keeps the recalculation, painting and layout to a minimum.

If you ever find yourself appending a series of elements to the DOM, you should always use a DocumentFragment to do just that.

A DocumentFragment is a minimal document object that has no parent.It is used as a light - weight version of document to store well - formed or potentially non - well - formed fragments of XML.
https: //developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
load more v
75%

You can also manipulate an element’s HTML directly using innerHTML like this:,You can new elements to the div element by creating an element and appending it:,Using innerHTML is cleaner and shorter when you want to add attributes to the element:,Summary: in this tutorial, you’ll learn the difference between the innerHTML and createElement() when it comes to creating new elements in the DOM tree.

Suppose that you have a div element with the class container:

.wp-block-code {
	border: 0;
	padding: 0;
}

.wp-block-code > div {
	overflow: auto;
}

.shcb-language {
	border: 0;
	clip: rect(1px, 1px, 1px, 1px);
	-webkit-clip-path: inset(50%);
	clip-path: inset(50%);
	height: 1px;
	margin: -1px;
	overflow: hidden;
	padding: 0;
	position: absolute;
	width: 1px;
	word-wrap: normal;
	word-break: normal;
}

.hljs {
	box-sizing: border-box;
}

.hljs.shcb-code-table {
	display: table;
	width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
	color: inherit;
	display: table-row;
	width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
	display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
	white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
	white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
	border-spacing: 0;
	counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
	counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
	padding-left: 0.75em;
}

.hljs.shcb-line-numbers .shcb-loc::before {
	border-right: 1px solid #ddd;
	content: counter(line);
	display: table-cell;
	padding: 0 0.75em;
	text-align: right;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
	white-space: nowrap;
	width: 1%;
}<div class="container"></div>Code language: HTML, XML (xml)
load more v
40%

I was reading about document fragments and DOM reflow and wondered how document.createDocumentFragment differed from document.createElement as it looks like neither of them exist in the DOM until I append them to a DOM element.,Anyway, based on the example below, why should I use createDocumentFragment instead of createElement when inserting into the DOM and whats the differnce between the two. ,I did a test (below) and all of them took exactly the same amount of time (about 95ms). At a guess this could possibly be due to there being no style applied to any of the elements, so no reflow maybe. ,Your current method fails, because HTML properties are not defined for the given XML document. If you supply the text/html MIME-type, the method should work.

Anyway, based on the example below, why should I use createDocumentFragment instead of createElement when inserting into the DOM and whats the differnce between the two.

var htmz = "<ul>";
for (var i = 0; i < 2001; i++) {
    htmz += '<li><a href="#">link ' + i + '</a></li>';
}
htmz += '<ul>';

//createDocumentFragment
console.time('first');
var div = document.createElement("div");
div.innerHTML = htmz;
var fragment = document.createDocumentFragment();
while (div.firstChild) {
    fragment.appendChild(div.firstChild);
}
$('#first').append(fragment);
console.timeEnd('first');

//createElement
console.time('second');
var span = document.createElement("span");
span.innerHTML = htmz;
$('#second').append(span);
console.timeEnd('second');


//jQuery
console.time('third');
$('#third').append(htmz);
console.timeEnd('third');
load more v
22%

Normally when using CreateDocumentFragment the document.CreateElement and other manipulation methods are used to build and complete the fragment.,The method returns a DocumentFragment object. This is the same object returned from a selector method like querySelector. It has the full battery of methods you can use for any element.,One of these native JavaScript APIs is the createDocumentFragment method.,This is because the nodes created by the CreateDocumentFragment method are not part of the DOM, they reside in memory.

The function creates a wrapping DIV element and adds the markup string to it using the DIV's innerHTML property. At this point you have a valid DIV element with child elements, assuming the string you passes has HTML in it.

 function createFragment(htmlStr) {
    var frag = document.createDocumentFragment(),
       temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
       frag.appendChild(temp.firstChild);
    }
    return frag;
 }
load more v

Other "undefined-undefined" queries related to "Should I use document.createDocumentFragment or document.createElement"