Setting CSS pseudo-class rules from JavaScript

user39882 picture user39882 · Nov 22, 2008 · Viewed 98.3k times · Source

I'm looking for a way to change the CSS rules for pseudo-class selectors (such as :link, :hover, etc.) from JavaScript.

So an analogue of the CSS code: a:hover { color: red } in JS.

I couldn't find the answer anywhere else; if anyone knows that this is something browsers do not support, that would be a helpful result as well.

Answer

bobince picture bobince · Nov 22, 2008

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.