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.
source to share
.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 .
source to share