fiddle
The following code alerts empty string:
HTML:
<div id="test">test</div>
CSS:
#test{
background-color: #f00;
}
SCRIPT:
alert(document.getElementById('test').style.backgroundColor)
But if I set bgcolor in javascript then it would alert the bgcolor value:
document.getElementById('test').style.backgroundColor='#ff0';
alert(document.getElementById('test').style.backgroundColor) // rgb(255,255,0)
So, how can I get the bgcolor value without setting it in js that is defined in stylesheet?
Note that I don't want to get a value at all if it comes from the user agent's stylesheet rather than mine.
The reason you're not seeing anything from .style
is that that only gives you the styles set on the element, not ones it receives from stylesheets.
For modern browsers, you can use window.getComputedStyle
to get the computed style object for the element. For IE8 (and earlier, but...), you can use .currentStyle
to get much the same thing. So:
var element = document.getElementById('test');
var style;
if (window.getComputedStyle) {
style = window.getComputedStyle(element);
} else {
style = element.currentStyle;
}
if (!style) {
// ...seriously old browser...
} else {
alert(style.backgroundColor);
}
I just want to get stylesheet value.
getComputedStyle
/currentStyle
will give you that, but will also give you the browser's default style.
There's no simple interface to get only the value from your own stylesheets and not from the user agent's default stylesheet. You might want to look at the document.styleSheets
property, which gives you access to the individual parsed stylesheets and their rules. But you'd have to handle the logic of applying those rules to the element in question, which is (of course) non-trivial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With