"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">
|
|
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">
|
|
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 |