doesn't work with external CSS stylesheet

Can anyone tell me why

doesn't work with external CSS stylesheet? I mean: when I have

    background-color: red;   


in my CSS stylesheet. javascript alert alert(;

shows empty string. Working example here .

but when i have

<body style="background-color: red;"></body>


it shows (as it should) "red". An example is here .

I would appreciate a good explanation and even more for an answer on how to fix the first example.


source to share

3 answers


a property on a DOM element returns CSSStyleDeclaration

for that specific element. By access definition, .style

these are the styles of the element itself. The attribute style=

controls the same value, so you see the result.

However, the CSS applied with the selector is not directly a property of the element. Consider CSS p { color: red }

. This CSS applies to multiple elements and as such it doesn't make sense to be overridden at the level of a specific element.

What you are looking for is window.getComputedStyle

to get a read-only view of the styles of the current element: window.getComputedStyle(document.body).backgroundColor

does indeed return the correct value as shown in the updated Fiddle .



you are using jquery buddy

try this it will give rgb value



Js Fiddle

if you want to use hex value try this

Js Fiddle



try it

var element =     document.getElementsByTagName('body')[0];                     
var style = window.getComputedStyle(element),
var bgColor    = style.getPropertyValue('background-color');




All Articles