Read :hover pseudo class with javascript

Using getComputedStyle as on the accepted answer won’t work, because:

  1. The computed style for the hover state is only available when the element is actually on that state.
  2. The second parameter to getComputedStyle should be empty or a pseudo-element. It doesn’t work with :hover because it’s a pseudo-class.

Here is an alternative solution:

function getCssPropertyForRule(rule, prop) {
    var sheets = document.styleSheets;
    var slen = sheets.length;
    for(var i=0; i<slen; i++) {
        var rules = document.styleSheets[i].cssRules;
        var rlen = rules.length;
        for(var j=0; j<rlen; j++) {
            if(rules[j].selectorText == rule) {
                return rules[j].style[prop];
            }
        }
    }
}

// Get the "color" value defined on a "div:hover" rule,
// and output it to the console
console.log(getCssPropertyForRule('div:hover', 'color'));

Demo

Leave a Comment