Skip to content Skip to sidebar Skip to footer

Difference Between Body.style.backgroundcolor And Window.getcomputedstyle(body).getpropertyvalue('background-color')

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

Solution 1:

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

Solution 2:

Actually, document.body.style.backgroundColor will get only inline style property of an element like this

<bodystyle="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.

Solution 3:

just using body.style.backgroundColor will only be able to sense if an inline style is on the body and give you that (e.g. a style applied via the style attribute in the html or using the style property in JavaScript). getComputedStyle also gets styles that were applied to it via stylesheets in <style> tags, inherited styles from parent elements, and everything.

In short, body.style.backgroundColor will get the background color that was in the style attribute (<body style="background-color:red>) or applied through JavaScript, getComputedStyle will also be able to get style from stylesheets (<style>body{background-color:red}</style>)

Solution 4:

If you have

background-color: red !important;

anywhere in your .css files, or <style> elements, that will override inline style e.g. style="background-color: blue;"

Post a Comment for "Difference Between Body.style.backgroundcolor And Window.getcomputedstyle(body).getpropertyvalue('background-color')"