JS/CSS: backgroundColor for second class

Viewed 57

I am grabbing the element below like:

let box = document.querySelector('.zero');

When I go to check the backgroundColor in javascript, it shows as "" :

 box.style.backgroundColor    // ""

If I'm grabbing the element node, why doesn't it list the backgroundColor as #DCDCDC, like what I set it in my CSS as? I assume it's due to the multiple classes on the element but not sure why.

code:

<div class="tic-tac-box zero">
</div>


.tic-tac-box {
    background-color: #DCDCDC;
    border-radius: 5px;
    border: 2px solid white;
}
1 Answers

The reason it's not logging the color is not because there are multiple classes, but because how the DOM API works, and that Javascript doesn't know what's going on with your linked CSS. If you want to log the current style of your element you'll have to use the getComputedStyle() method:

getComputedStyle(box).backgroundColor); // rgb(220, 220, 220)

tldr: "The style property only retrieves inlined CSS values while getComputedStyle style retrieves computed CSS values." Check out this article for more info. You'll notice when you set colors with that syntax, it appends inline styles too.

Related