Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get `background-color` property value in Javascript? [duplicate]

Tags:

javascript

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.

like image 523
Navin Rauniyar Avatar asked Sep 03 '25 08:09

Navin Rauniyar


1 Answers

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.

like image 84
T.J. Crowder Avatar answered Sep 04 '25 20:09

T.J. Crowder