Creates a new empty DocumentFragment
.
Syntax
var docFragment = document.createDocumentFragment();
docFragment
is a reference to an empty DocumentFragment
object.
Description
DocumentFragment
s are DOM Nodes. They are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children.
Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Consequently, using document fragments often results in better performance.
documentFragment
are supported in all browsers, even Internet Explorer 6, so there is no reason to not use them.
Example
var ul = document.getElementsByTagName("ul")[0]; // assuming it exists
var docfrag = document.createDocumentFragment();
var browserList = ["Internet Explorer", "Mozilla Firefox", "Safari", "Chrome", "Opera"];
browserList.forEach(function(e) {
var li = document.createElement("li");
li.textContent = e;
docfrag.appendChild(li);
});
ul.appendChild(docfrag);
// a list with well-known web browsers
Browser compatibility
Specification
- DOM Level 2: createDocumentFragment
- DOM Level 3: createDocumentFragment