Dynamic Style Sheets

This isn’t about rotating through alternate stylesheets or importing them, or even changing an inline style on an element through Javascript. Oh no. This is about creating an actually stylesheet element ON THE FLY.

The reason for this is because for a bit I was just trying to create a long string with the style tags and rules inside it, and then just pop it in the innerHTML of the body. (Hey, I’m no Guru, I have a lot to learn!) Needless to say, this caused a few issues.

At first I tried to use DOM Stylesheets to serve my purposes, but I soon found that although they work in Mozilla and IE (though IE works funny and has different functions to use), the document.stylesheets object and it’s functions are woefully supported in other browsers, Safari in particular.

My next attempt was a tad more successful - I used document.createElement("style"), appended the rules to it as a TextNode, and then appended the style to the <head>. I then learned that IE does not like to append TextNodes to style elements.

So, after a bit of research I found a way to get IE to insert the text into the style. It works in the latest-greatest Mozilla, IE, Safari, and Opera. Not sure about older versions. Just have it run onLoad() and make an example div to test it out.

var myCSS = "div{background-color: blue}";
var myStyle = document.createElement("style");
	myStyle.setAttribute("type", "text/css");

//only IE uses style.styleSheet, the rest use style.sheet
if(myStyle.styleSheet){
	//Many browsers won't let you change the style's cssText, but IE does.
	myStyle.styleSheet.cssText = myCSS;
} else {
	//this is the standard way to do it, which IE does not support.
	myCSS = document.createTextNode(myCSS);
	myStyle.appendChild(myCSS);
}

document.getElementsByTagName("head")[0].appendChild(myStyle);

Obviously if you don’t want things to blow up in more archaic browsers, you’re going to want to do a detect for document.createElement before running this code.

Leave a Comment