tags:

views:

323

answers:

4

How do you add CSS rules (eg strong { color: red }) by use of Javascript?

+4  A: 

The simple-and-direct approach is to create and add a new style node to the document.

var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = "strong { color: red }";
document.body.appendChild(css);
Ben Blank
Shouldn't it be appended to the document's head rather than body?
bobince
Technically, I guess maybe, but it works...
nickf
@bobince — According to the HTML specs, absolutely, but all browsers recognize them anywhere. `document.body` is also shorter to type and faster to execute than `document.getElementsByTagName("head")[0]` and avoids the cross-browser issues of insertRule/addRule.
Ben Blank
+2  A: 

You can also do this using DOM Level 2 CSS interfaces:

sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

...on all but (naturally) IE, which uses its own marginally-different wording:

sheet.addRule('strong', 'color: red;', -1);

There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.

You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.

bobince
"color" .. oh yeah, oops! thankfully that was just an example. I suspected there might be a DOM method for this, thanks! +1
nickf
+2  A: 

YUI just recently added a utility specifically for this.

Russell Leggett
I'm currently using YUI for my work and was trying to figure out how to edit external style sheets of existing css rules. Didn't know about this utility, it seems perfect! Thanks Russell.
Jaime
A: 

You can add classes or style attributes on an element by element basis.

For example:

<a name="myelement" onclick="this.style.color='#FF0';">text</a>

Where you could do this.style.background, this.style.font-size, etc. You can also apply a style using this same method ala

this.className='classname';

If you want to do this in a javascript function, you can use getElementByID rather than 'this'.

mingala