Setting CSS pseudo-class rules from JavaScript

You can’t style a pseudo-class on a particular element alone, in the same way that you can’t have a pseudo-class in an inline style=”…” attribute (as there is no selector).

You can do it by altering the stylesheet, for example by adding the rule:

#elid:hover { background: red; }

assuming each element you want to affect has a unique ID to allow it to be selected.

In theory the document you want is http://www.w3.org/TR/DOM-Level-2-Style/Overview.html which means you can (given a pre-existing embedded or linked stylesheet) using syntax like:

document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor="red";

IE, of course, requires its own syntax:

document.styleSheets[0].addRule('#elid:hover', 'background-color: red', 0);
document.styleSheets[0].rules[0].style.backgroundColor="red";

Older and minor browsers are likely not to support either syntax. Dynamic stylesheet-fiddling is rarely done because it’s quite annoying to get right, rarely needed, and historically troublesome.

Leave a Comment