Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.body.style.backgroundColor doesn't work with external CSS style sheet [duplicate]

Could anyone tell me why document.body.style.backgroundColor doesn't work with external CSS style sheet? I mean: when I have

body
{
    background-color: red;   
}

in my css style sheet 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". Example here.

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

like image 737
KaroCodes Avatar asked Sep 27 '14 12:09

KaroCodes


1 Answers

.style property on a DOM element returns a CSSStyleDeclaration for that particular element. By definition of a .style access, it is the styles of the element itself. style= attribute controls the same value, thus you see the result.

However, CSS applied using a selector are not directly a property of an element. Consider the CSS p { color: red }. This CSS applies to multiple elements, and as such, make no sense being overrideable on a level of a particular element.

What you are looking for is window.getComputedStyle to get a read-only view on the element's current styles: window.getComputedStyle(document.body).backgroundColor indeed returns a correct value, as seen in the updated Fiddle.

like image 113
Denis Avatar answered Sep 25 '22 05:09

Denis