Search code examples
javascriptjquerycsscss-selectorspseudo-class

How to access the focus/hover/visited CSS properties of an element through Javascript?


I may be tired and thinking oddly right now, but I simply cannot find how to retrieve the values of CSS properties defined in an element's focused, hovered or visited states. The goal is to use the values in Javascript.

Important: I do not need to get the focused/hovered/visited elements. I want to access certain values of any element in the DOM with CSS properties defined for the following states: :focus, :hover and :visited.

These pseudo-classes do not seem to help in this case, so do I need to trigger the respective state in order to access the values?

It should be simpler than this... Or is it not?

P.S.: Answers in vegetarian Javascript or jQuery will do.


Solution

  • Yes you can achieve this by reading style sheets. You can get it by using document.styleSheets; Below is the example and jsfiddle link.

    http://jsfiddle.net/wt3qQ/

    For security reasons, Opera and Mozilla will not allow you to access the cssRules collection of a stylesheet from another domain or protocol. Attempting to access it will throw a security violation error

    function getStyleBySelector( selector )
       {
           var sheetList = document.styleSheets;
           var ruleList;
           var i, j;
    
           /* look through stylesheets in reverse order that
              they appear in the document */
           for (i=sheetList.length-1; i >= 0; i--)
           {
               ruleList = sheetList[i].cssRules;
               for (j=0; j<ruleList.length; j++)
               {
                   if (ruleList[j].type == CSSRule.STYLE_RULE && 
                       ruleList[j].selectorText == selector)
                   {
                       return ruleList[j].style;
                   }   
               }
           }
           return null;
       }
    
    console.log(getStyleBySelector('a:hover').color);
    console.log(getStyleBySelector('#link:hover').color);