Navigation
Poll
Would you be an active poster if Ron's Guide had a message board?


Total Votes: 62
Comments: 18 — View
Past pollsPoll idea?
Rate Ron's Guide
Rate our resource at Bigwebmaster.com
createDocumentFragment()
In this tutorial I will show you how to create a new document fragment and append a new node to it before appending it to the document.

"createDocumentFragment()" is basically somewhere to store your newly created nodes before you append them to the document. When you are ready to append all the nodes to the document, all you need to do is one 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>

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 using the "createTextNode()" method, 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 doing 15 appendChild()'s at the end of my script, I can just do the one, which would be to append the document fragment. 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, so it's just a matter of appending it to the document.

Discuss Tutorial: createDocumentFragment() 0 Comments
There are currently no comments on this discussion.
Post a comment
Sorry, you must be a registered member to post comments.

If you would like to register, you can do so here.
If you already have an account, please login.