Setting CSS pseudo-class rules from JavaScript
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.
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.
I threw together a small library for this since I do think there are valid use cases for manipulating stylesheets in JS. Reasons being:
- Setting styles that must be calculated or retrieved - for example setting the user's preferred font-size from a cookie.
- Setting behavioural (not aesthetic) styles, especially for UI widget/plugin developers. Tabs, carousels, etc, often require some basic CSS simply to function - shouldn't demand a stylesheet for the core function.
- Better than inline styles since CSS rules apply to all current and future elements, and don't clutter the HTML when viewing in Firebug / Developer Tools.