2

I need help, I want to get element:hover all styles. For example:

<style type="text/css">
a {color: red;}
a:hover {color: blue;}
</style>

Using jquery we can find "a" element default style:

$('a').css('color');

and it will be return as string: "red";

But now I want to get pseudo styles, like this:

$('a:hover').css('color');

and it will be return "undefined", but we need "blue".

Please help me solve this problem...


Developer9621
  • 111
  • 1
  • 2
  • 9

4 Answers4

4

Pure Javascript does it!

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];
                }
            }
        }
    }

 alert("Hovered Colour is "+getCssPropertyForRule('a:hover', 'color'));

Here is a Working example jsfiddle

natchkebiailia
  • 611
  • 4
  • 18
  • 1
    This only works if you happen to know the exact selector used in the CSS... – Chris_F Dec 09 '16 at 19:17
  • Thank you so much!!! I used this in combination with another function to change the ```a``` & ```a:hover``` colors. I needed to do thus via a button (for my web app), so I couldn't rely on CSS alone. – Supertecnoboff Jun 23 '17 at 11:36
1

That is because there is no element a with type :hover. So it would always return a undefined.

And I don't think you can get the pseudo class properties using jQuery or JavaScript until you get all the styles and then check for the element's property in that file.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
-1
var color = window.getComputedStyle(
    document.querySelector('a'), ':hover'
).getPropertyValue('color')

Check this link for extra information.

bobthedeveloper
  • 3,733
  • 2
  • 15
  • 31
-1

You can use .hover() function instead. http://api.jquery.com/hover/

$( "a.foo" ).hover(
  function() {
    $( this ).css( 'color','red' );
  }, function() {
    $( this ).css( 'color','blue');
  }
);
Santosh Achari
  • 2,936
  • 7
  • 30
  • 52