When we are constructing a combination of new nodes to add into the web page we can easily make sure that we add all of our child nodes in the order that we want them to appear in the page. We can't do this if child nodes that need to come after the new nodes already exist in the web page.
The solution to this is to not use the appendChild method to add the new node into the page but to instead use the insertBefore method. This method needs to be attached to the same parent node as we'd use for appendChild but instead of just specifying the new node to add to the end we need to specify both the new node and the existing node that we want to insert before.
Since we need the node we are inserting before anyway it makes sense to start from that one in the web page since we can easily obtain its parent node (which is the one both nodes will be children of). This helps avoid the possible error that would arise if the node to insert before wasn't in fact a child of the one we are running the method on.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
<div><p id="bf">New paragraph to be added before this one.</p></div>
var exP, newP;
newP = document.createElement("p");
newP.id = 'new'; exP = document.getElementById('bf');