matanox
matanox

Reputation: 13686

Correctly setting and inquiring background color in Chrome (from Javascript)

Following is a Chrome dev tools console session of manipulating text to having a red background.

One may notice the difference between background-color and backgroundColor which may seem to present an odd relationship in this case.

> document.getElementById('38').style.backgroundColor = 'red'
"red"

> window.getComputedStyle(document.getElementById('38')).getPropertyValue('background-color')
"rgb(255, 0, 0)"

> window.getComputedStyle(document.getElementById('38')).getPropertyValue('backgroundColor')`
null

How can this be explained?

The text does turn red in the browser, but the api may seem a bit quirky. What may I be doing wrong?

Upvotes: 0

Views: 244

Answers (1)

Michael Radionov
Michael Radionov

Reputation: 13309

According to Mozilla docs .style is used to modify CSS properties of an element through a "style" attribute of an element

<div style="background-color: red"></div>

But it does not give you a full representation of styles state of an element i.e. .style does not contain all computed styles.

Here you can see available shortcuts for CSS properties that are used with .style.

In this list in first column for background we have an original name of CSS property - 'background-color' and a shortcut that is used with .style - 'backgroundColor'

Using .getPropertyValues(prop) seems to use a value from first column prop = 'background-color', that is pretty similar to CSS original property name

For .style[prop] you use a value from second column prop = 'backgroundColor'.

Question with a similar problem

Upvotes: 2

Related Questions