Working with JavaScript again and wanting to prepend an element to the page

I am getting back into the swing of using JavaScript again and I am dynamically adding elements to the page quite easily using

var elem1 = document.createElement("div");
... some code to do something ...
document.getElementsByTagName("body")[0].appendChild(elem1);

Which simply adds the new element to the end of the page, or if I had appended it to an element in the page it would appear at the end of that element. However I needed it to be generated at the front of the dom element before any others.

I had done this before but thanks to the wonders of google I quickly found what I needed to know. Now yes it would be very easy to do this using jQuery but that involved adding another library to the page, this would have been silly seeing this was the only thing required. What I forgot about was the good old insertBefore()

var theparentElement = document.getElementById("container");
var elem1 = document.createElement("div");
... some code to do something ...
theparentElement.insertBefore(frame, theparentElement.firstChild);

For reference the most useful site on the subject I found in the 20 seconds of looking was http://developer.practicalecommerce.com/…

Leave a Reply