1. Technology

The Javascript DOM

12. insertBefore

clr gif

Using appendChild to add objects to the web page has one problem. It only allows us to add within the end of an existing container on the page. What do we do if we want to add an object somewhere other than at the end of its new parent? We ause the insertBefore method instead.

insertBefore is slightly different from the DOM methods we have looked at so far because it takes two parameters. Instead of just soecifying the new object to be inserted as we do with the appendChild method we also need to supply the object within the parent container before which the new object is to be added.

Imagine if instead of inserting our paragraph from a couple of tutorials back at the end of the page we want to insert it before the second paragraph already on the page (for example). Well we have already seen the code to create our container and text and to add the text into the container. We have also seen (in earlier tutorials) how to retrieve a specific object from the page (in this instance the second paragraph). All we have to do after putting that code together is to add one last line to tell the DOM to insert the new object before the existing one.

var newP = document.createElement("p");
var txt = 'Kilroy was here.';
var newT = document.createTextNode(txt);
newP.appendChild(newT);
var p2 = document.getElementsByTagName('p')[1];
p2.parentNode.insertBefore(newP,p2);

©2014 About.com. All rights reserved.