Join the Discussion
By now you will have realised that the standard DOM methods process one container at a time. This means that in order to add several adjacent containers we would need to add thm one at a time and they would appear one at a time rather than all together.
Where our containers are all nested within one another we can of course add the inner containers to the outer one before adding that largest container to the page. For example to add a paragraph containing bold text we would:
Now you know why innerHTML is so popular since it can do all of this in one command (provided that the container already exists in the page so you'd still need to create the paragraph and add it to the page before being able to fill it using innerHTML - and that would again lead to the paragraph appearing first and then the content which doesn't happen if we follow the above steps using the standard DOM).
Where we want to insert multiple paragraphs we can either insert them one at a time or we can set up a div container and add them all into that before adding them to the page. That leads to an extra div in or page though that we don't really want and would make subsequent changes to the page more complex. There is a better way.
The createDocumentFragment method allows us to attach several containers together into one object without our having to have an outer container that surrounds all of the content. So instead of adding our paragraphs to the page one at a time, we create a document fragment and add them one at a time to that instead. Once the fragment contains all of the content that we want to add to our page (or use to replace part of the existing content of the page) we can then use the appropriate method to insert the whole fragment into the web page in one go rather than addint the pieces individually.
Doing this means that we still have to build up our object one piece at a time but that the construction of the object is completely invisible to our visitors as the entire object is added in one go once the entire thing has been created.
Heres an example where we insert two paragraphs at once.
var newP = document.createElement("p");
var txt = 'Kilroy was here.';
var newT = document.createTextNode(txt);
var newP2 = document.createElement("p");
var txt2 = 'No he wasn\'t.';
var newT2 = document.createTextNode(txt2);
var frag = document.createDocumentFragment();
var p2 = document.getElementsByTagName('p');