3

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;
}
  • 3
    Most likely need to use `getcomputedstyle` instead. Since javascript is looking for the inline style and not the applied css. – imvain2 Jan 20 '21 at 20:24
  • Like @imvain2 says you will want `getcomputedstyle`, the `element.style`, is what your putting inside `` or what you might have set using `setAttribute('style`,'')` etc. – Keith Jan 20 '21 at 20:29
  • window.getComputedStyle(box).backgroundColor will do it – Ashish Kumar Jan 20 '21 at 20:35
  • getComputedStyle gives the rgb colour for the hex value, might not be the intended result? – Nathaniel Flick Jan 20 '21 at 20:35
  • I deleted my answer, there's a better answer here for how to get the CSS values instead of the computed values: https://stackoverflow.com/questions/46828223/get-css-not-computed-property-value-with-javascript-only – Nathaniel Flick Jan 20 '21 at 20:46
  • Does this answer your question? [How to retrieve the display property of a DOM element?](https://stackoverflow.com/questions/3778335/how-to-retrieve-the-display-property-of-a-dom-element) – Heretic Monkey Jan 20 '21 at 21:10
  • It works with getComputedStyle. Thanks. I didn’t realize style.backgroundColor only grabbed the inline styling. – DevQuestions21 Jan 20 '21 at 21:46

1 Answers1

4

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.

G-mo
  • 56
  • 2