Creating new CSS stylesheets with Javascript
This isn’t documented anywhere as far as I can tell, and it took me a long time to figure out, so I thought I’d write it down.
I want to create a new CSS stylesheet, apply it to a document, and dynamically fill its contents.
In Mozilla/Firefox, Safari, and Opera, you can create a style sheet DOM node, fill its contents, and insert it into the head of your document like this:
var styleText = "body{background-color:blue;}";
var head=document.getElementsByTagName("head")[0];
var styleNode = document.createElement("style");
styleNode.appendChild(document.createTextNode(styleText));
head.append(styleNode);
IE doesn’t allow you to append style nodes to the head of your document. Instead, you can use the IE-only createStyleSheet, and set its cssText property:
var styleText = "body{background-color:blue;}";
var s = document.createStyleSheet("");
s.cssText=styleText;


