Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('background-color')

Given that var body = document.getElementsByTagName("body")[0];

Is there any other way I can get the background-color?

like image 394
Hommer Smith Avatar asked Feb 14 '23 16:02

Hommer Smith


2 Answers

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

like image 84
RobG Avatar answered Apr 29 '23 00:04

RobG


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.

like image 32
The Alpha Avatar answered Apr 29 '23 01:04

The Alpha