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.
.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.
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