I am trying to get the background color of the body, and I am wondering what is the difference between:
body.style.backgrounColor
and
window.getComputedStyle(body).getPropertyValue('background-color')
Given that var body = document.getElementsByTagName("body")[0];
Is there any other way I can get the background-color?
Using:
document.body.style.backgroundColor
sets the style directly on an element, or returns the current value of the related style property that has been set through the style attribute or property. Such values are considered by a user agent when determining how to display an element when applying CSS rules (if there are any).
An element's style object does not necessarily reflect values applied to an element through CSS rules, though they may be the same (by chance or deliberately setting both to the same value).
The order in which style rules are applied to an element are listed in the CSS2.1 spec. Rules applied directly to the element are of second highest precedence, after !important
declarations.
Using:
window.getComputedStyle(document.body, null).getPropertyValue('background-color')
is described in the DOM Level 2 specification. Basically, it returns the current style property values being used to display an element based on CSS rules, i.e. what is actually being applied to the element.
This often different to the value of the related style property (which not have a value unless set by a property or attribute).
Actually, document.body.style.backgroundColor
will get only inline
style property
of an element like this
<body style="background-color:red">
On the other hand window.getComputedStyle
will get
the actual property after CSS
and styles are applied to the element, for example, this is possible to get using window.getComputedStyle
body{
background-color:#fff;
}
But it's not possible to read css
style given above using document.body.style.backgroundColor
. Check this example. Also, check this.
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