I am reading a code snippet in my application that goes like:
// Fragment Constructed
fragment = new Object();
fragment.document = document.createElement("div");
fragment.parentNode = node.parentNode; // Remembers the position to re-attach
fragment.nextSibling = node.nextSibling; // Remembers the position to re-attach
fragment.document.appendChild(node);
//Fragment Re-attached
if (fragment.nextSibling && fragment.nextSibling.nodeType !== 3) {
while (fragment.document.firstChild) {
fragment.parentNode.insertBefore(fragment.document.firstChild, fragment.nextNode);
}
} else {
while (fragment.document.firstChild) {
fragment.parentNode.appendChild(fragment.document.firstChild);
}
}
When the user clicks on a YUI Panel Hide button, we create an Object
which has the following properties - parentNode, nextSibling of the panel box and a documentFragment
object which gets appended with the panel container itself (i.e Fragment Contructed code above).
When the user unhides the YUI Panel, we re-attach it to the DOM. (i.e Frament Re-attached code above).
While I am still trying to figure how it works in real time covering all the different node possibilities, I had some questions about this code snippet.
- Would the
fragment.document.firstChild
be always 1 because I am appending a single node usingfragment.document.appendChild(node)
? - If the
nextSibling
exists and it is atextnode
this code goes to the else condition, but does it actually retain the correct meaning because we are now just appending to the parent without worrying about order correct? I guess this condition should be removed and it would work fine? - What is the algorithmic complexity of
while(fragment.document.firstChild)
? Is it O(n) where n is the number of child nodes regardless of the child node it has - i.e child's child etc. - Are there any advantages in doing this? I.e we are storing it elsewhere and bringing it back. Is there any advantage in doing so?
Related Question: Should I use document.createDocumentFragment or document.createElement