createDocumentFragment()

Creator:
Peter

createDocumentFragment() is basically somewhere to store your newly created nodes before you append them to the document, then when you are ready to append all the nodes to the document, all you need to do is 1 append and they all get added.

Creating a fragment is extremely easy. Have a look at the example below to see how a fragment is created.

<script type="text/javascript">
<!--
var docFragment = document.createDocumentFragment();
//-->
</script>

Simple see? Nothing to it, you now have somewhere to store your new nodes. To add nodes to the fragment, all you need to do is append the childs to the fragment. See the example below to understand what I mean.

<script type="text/javascript">
<!--
var docFragment = document.createDocumentFragment();
var txt = document.createTextNode("my text node");
docFragment.appendChild(txt);
//-->
</script>

For the example above I created a new text node, and then used appendChild() to append the new text node to my fragment. So now my fragment holds 1 node. I could add more if I wished.

So what's the point in using it when you can just keep using appendChild()? To be honest I haven't found a big need to use it, but when I have, I use it when I do a lot of appending to the document. So instead of do 15 appendChild()'s at the end of my script, I can just do the 1, which would be to append the fragment, because throughout the script I will be appending them to the fragment, so when it comes to the end of my script all the new created nodes would now be stored in my fragment, just a matter of appending it to the document.

I'm sure there is more use for it then that, just that I haven't found a big need for it.

Description:
Basic tutorial on how to create a fragment and append new nodes to it before appending it to the document.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options