Dynamically link to CSS with JavaScript

Needed a way to add a CSS file with JavaScript, so I went out a-Googling like I normally do.  Problem is everything I found either worked in Internet Explorer and not in FireFox or the other way around.  Nothing I found worked in both.  So I hacked together a function of my own.  Should have just started with it since it took less time to write than the time I spent searching.

function addCSS(link) {
    var styleEl = document.createElement('link');
    styleEl.type = 'text/css';
    styleEl.href = link;
    styleEl.rel = 'stylesheet';
    document.getElementsByTagName('head')[0].appendChild(styleEl);
}
This entry was posted in Internet, Programming and tagged , . Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>