Document.body.style.backgroundColor doesn't work with external CSS stylesheet

Can anyone tell me why document.body.style.backgroundColor

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

body
{
    background-color: red;   
}

      

in my CSS stylesheet. javascript alert alert(document.body.style.backgroundColor);

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.

+3


source to share


3 answers


.style

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 .

+3


source


you are using jquery buddy

try this it will give rgb value

alert($('body').css('background-color'));

      



Js Fiddle

if you want to use hex value try this

Js Fiddle

+1


source


try it

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

      

+1


source







All Articles