I'm playing around with a document fragment
. I find it hard to understand how it behave when I append it to the DOM.
I create a doc fragment
that I assign to a variable, when I insert some stuff into it, and append the doc fragment into a element. But if I clear the element
my variable which should reference to the doc fragment contain an empty document fragment.
I trying to make a cache for a third party lib that creates document fragments. So I would like to get this working. Should I create a cloneNode before I append the fragment to the DOM, is that correct?
I have created a JS fiddle: http://jsfiddle.net/4CTXG/1/
var test = document.createDocumentFragment();
//var test = document.createElement("div"); // This one work
$(test).append($("<div>").html('Hello world!'));
$("#result").append(test);
setTimeout(function(){
$("#result").children().remove();
$("#result").append(test);
console.log('Now test should have been appended');
$(result).css({"background": "#FF0000"});
},5000)
The DocumentFragment interface represents a minimal document object that has no parent. It is used as a lightweight version of Document that stores a segment of a document structure comprised of nodes just like a standard document.
The createDocumentFragment() method creates an offscreen node. The offscreen node can be used to build a new document fragment that can be insert into any document.
createContextualFragment() method returns a DocumentFragment by invoking the HTML fragment parsing algorithm or the XML fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node.
Paste your HTML code into the large HTML Code box. Choose between the 'Manual', 'Head' and 'Body' types. Click the Add HTML Fragment button. You will be returned to the HTML Fragments screen where your new fragment will now be listed.
When you append an Element (e.g. the <div>
) into the DOM, the Element gets added as a child of its new parent. The div's children are not changed. When you remove the element from its parent, the Element is just detached from the DOM. It you still have a reference to the Element it will still contain its children, available to reattach later.
When you append an DocumentFragment into the DOM, the children of the DocumentFragment are removed from the DocumentFragment and moved to be children of its DOM element parent. The DocumentFragment is now empty.
So instead of appending the DocumentFragment, you should append a deep clone of the fragment.
See http://dom.spec.whatwg.org/#concept-node-insert for the gory details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With