Welcome to the adventure

Creating new CSS stylesheets with Javascript

Friday April 27, 2007

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;

1 Comment »

  1. Not solving your problem exactly, but look at
    http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript if you didn’t yet. Seems interesting.

    Said by myf April 30, 2007 at about 10:36 am

Leave a comment