I was reading about document fragments and DOM reflow and wondered how document.createDocumentFragment
differed from document.createElement
as it l
The difference is that a document fragment effectively disappears when you add it to the DOM. What happens is that all the child nodes of the document fragment are inserted at the location in the DOM where you insert the document fragment and the document fragment itself is not inserted. The fragment itself continues to exist but now has no children.
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
Another very important difference between creating an element and a document fragment:
When you create an element and append it to the DOM, the element is appended to the DOM, as well as the children.
With a document fragment, only the children are appended.
Take the case of:
var ul = document.getElementById("ul_test");
// First. add a document fragment:
(function() {
var frag = document.createDocumentFragment();
var li = document.createElement("li");
li.appendChild(document.createTextNode("Document Fragment"));
frag.appendChild(li);
ul.appendChild(frag);
console.log(2);
}());
(function() {
var div = document.createElement("div");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Inside Div"));
div.appendChild(li);
ul.appendChild(div);
}());
Sample List:
<ul id="ul_test"></ul>
which results in this malformed HTML (whitespace added)
<ul id="ul_test">
<li>Document Fragment</li>
<div><li>Inside Div</li></div>
</ul>