Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Element.style CSSStyleDeclaration object's properties look wired?

Let’s say I have a button in a html file,

<button id="btn">Click Me</button>

Use Javascript to change the color of that button to red.

const btn = document.querySelector('#btn');
btn.style['background-color'] = 'red';

Then I check the btn.style['background-color']. It shows red.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

btn.addEventListener('click', () => {
    console.log(`This button is in ${btn.style['background-color']}`)
});

So I suppose that my btn.style object should look like this,

{
...
"background-color": "red",
...
}

But when I print them in the console, why the key-value pair is 0: "background-color", and where is value red?

btn.addEventListener('click', () => console.dir(btn.style));

enter image description here

>Solution :

The CSSStyleDeclaration object is a bit exotic. If you look at btn.style["background-color"] or btn.style.backgroundColor directly, you’ll see red (or some representation of red, it varies by browser).

const btn = document.querySelector('#btn');
btn.style['background-color'] = 'red';

btn.addEventListener('click', () => {
    console.log(btn.style["background-color"]);
    console.log(btn.style.backgroundColor);
});
<button id="btn">Click Me</button>

In the console output you showed, you’ll find it under backgroundColor:

console output showing backgroundColor: red with a circle around it

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading