Setting CSS pseudo-class rules from JavaScript

  1. Home
  2. javascript
  3. 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.

First answer

Second answer

A function to cope with the cross-browser stuff:

addCssRule = function(/* string */ selector, /* string */ rule) {
  if (document.styleSheets) {
    if (!document.styleSheets.length) {
      var head = document.getElementsByTagName('head')[0];

    var i = document.styleSheets.length-1;
    var ss = document.styleSheets[i];

    var l=0;
    if (ss.cssRules) {
      l = ss.cssRules.length;
    } else if (ss.rules) {
      // IE
      l = ss.rules.length;

    if (ss.insertRule) {
      ss.insertRule(selector + ' {' + rule + '}', l);
    } else if (ss.addRule) {
      // IE
      ss.addRule(selector, rule, l);

Third answer

My trick is using an attribute selector. Attributes are easier to set up by javascript.


.class{ /*normal css... */}
.class[special]:after{ content: 'what you want'}


  function setSpecial(id){ document.getElementById(id).setAttribute('special', '1'); }


<element id='x' onclick="setSpecial("> ...  
Spread the love

Related articles

Comments are closed.