1

console.log(document.querySelector(".green").style.backgroundColor);
// gives an empty string as a result in console
.green {
  width: 200px;
  height: 200px;
  background-color: green;
}
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="src/styles.css">
</head>
<body>
    <div class="green"></div>
    <script src="src/index.js">
    </script>
</body>
</html>

I know that I can also use

window.getComputedStyle(document.querySelector(".green")).backgroundColor;

which is mentioned in this answer

but I want to know the reason behind this that why it is giving an empty string as a result.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415

3 Answers3

4

.style contains only inline styles (set via that property, or the HTML attribute with the same name). It's not affected by style sheets at all. getComputedStyle gets you the current effective value for that property, regardless of where it came from.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
3

You want the computed element style:

 console.log(getComputedStyle(document.querySelector(".green"), null).getPropertyValue("background-color"));
Stefan Avramovic
  • 1,365
  • 2
  • 11
  • 20
1

As is stated in the MDN Page for the element.style property:

The style property is used to get as well as set the inline style of an element.

Your element does not have a style attribute in which the background color is set-- as such, <yourelement>.style.backgroundColor returns an empty string. This is why getComputedStyle exists-- to allow you to interrogate the actual final/applied styles on an element, not merely those that might be inline on the element as a style attribute.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45