Jump to content

How to read CSS :pseudo elements with Javascript?


mikoro
 Share

Recommended Posts

I have this in my CSS file:a { color: red; }a:hover { color: green; }Then with Javascript I fetch the link element (to variable named link) and I read the color value:var color = link.style.color;How could I read the :hover color?var hoverColor = ?Thanks

Link to comment
Share on other sites

Ok, thanks. I stumbled into getComputedStyle when googling around and it looked like it would allow me to read the pseudo-information of an element. But not surprisingly it didn't work...I'd like to do this because at the moment I have to specify the same colors twice, once in css and once in my javascript file.

Link to comment
Share on other sites

This can be done using the styleSheets collection object. This code will read for both IE and Firefox. Note that it is enough to get you going, you will need to provide the looping to determine that you are reading the correct rule. Here's a good link for more info: http://www.javascriptkit.com/domref/cssrule.shtml<style> a {color:blue;} a:hover {color:red}</style><script> if(navigator.userAgent.indexOf("Firefox")!=-1) { document.write(document.styleSheets[0].cssRules[1].cssText) } if(navigator.userAgent.indexOf("IE")!=-1) { document.write(document.styleSheets[0].rules[1].style.color) }</script>

Link to comment
Share on other sites

  • 1 month later...
Guest Landskov
This can be done using the styleSheets collection object. This code will read for both IE and Firefox. Note that it is enough to get you going, you will need to provide the looping to determine that you are reading the correct rule. Here's a good link for more info: http://www.javascriptkit.com/domref/cssrule.shtml<style> a {color:blue;} a:hover {color:red}</style><script> if(navigator.userAgent.indexOf("Firefox")!=-1) { document.write(document.styleSheets[0].cssRules[1].cssText) } if(navigator.userAgent.indexOf("IE")!=-1) { document.write(document.styleSheets[0].rules[1].style.color) }</script>
Warning: document.styleSheets[0] does not necessarily contain the css rules you expect. I had to start with for (var j=0; j<document.styleSheets.length; j++) {to be sure that iterating through cssRules would reach the rule in my css file that I was interested in.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...