Recently I was asked to add an HTML code snippet containing external CSS and JS to a few different web pages. After having the code tested, of course Internet Explorer was the browser that caused me an issue. The stylesheets that were added were taking precedence for the styling in other elements that were supposed to remain unchanged. To fix the issue, I wrote a little JavaScript in order to prepend external stylesheets to the HEAD tag. This made me wonder how to prepend a node to any DOM element. Here is the code to do it:


function prependChild(parent, newChild) {
  parent.insertBefore(newChild, parent.firstChild);
}

Many people have suggested that this could be added to Element.prototype, but unfortunately that prototype doesn’t exist in every browser so the best way in this case would probably be to just have a simple function like the one above.

Categories: BlogJavaScript

3 Comments

FunnyDeveloper · March 13, 2013 at 8:00 AM

Thanks, it works.

Matías Lescano · June 30, 2016 at 6:18 PM

A litle fix to make it work when parent doesn’t have any childs:

function prependChild (parent, newChild) {
if (parent.firstChild) {
parent.insertBefore(newChild, parent.firstChild)
} else {
parent.appendChild(newChild)
}
}

    Chris West · August 17, 2016 at 12:48 PM

    In Chrome, Firefox, Internet Explorer (at least using Wine) and Safari the code works even if the parent doesn’t have any child nodes. Here is an example. Out of curiosity, is there a browser that you have seen this not work in?

Leave a Reply to Matías Lescano Cancel reply

Your email address will not be published. Required fields are marked *