Adding prependChild to Element

If you’ve ever done much DOM scripting, you have almost certainly used the appendChild function on Element. For instance, you might have done something like this:

var hello = document.createElement('p');
hello.innerText = 'Hello, world!';
document.getElementById('myDiv').appendChild(hello);

Nice and easy, but what if you want to prepend the child rather append? You could do this:

var hello = document.createElement('p');
hello.innerText = 'Hello, world!';
var myDiv = document.getElementById('myDiv');
myDiv.insertBefore(hello, myDiv.firstChild);

Or, you could just add a prependChild function to Element, like this:

Element.prototype.prependChild = function(child) { this.insertBefore(child, this.firstChild); };

Just make sure that the code above evaluates early on in your application initialization, and start prepending all you want. (Of course, if you’re using jQuery, prepend is already well in hand.)