'console.log of backgroundColor shows "" instead of the color value [duplicate]
I have an button element with id "btn". I want to console.log the background color property it shows blank instead. What is the problem? Thank you.
let btnColor = document.getElementById("btn").style.backgroundColor;
console.log(btnColor)
#btn{
display: block;
margin: auto;
width: 100px;
height: 100px;
border-radius: 3px;
background-color: #74992e;
}
<button id="btn">Click on me</button>
Solution 1:[1]
Use this:
let btnColor = window.getComputedStyle(document.getElementById(“btn”)).backgroundColor
console.log(btnColor)
it’s working fine for me
explain:
sometimes window.getComputedStyle will get the style object of an elem so that if you call .backgroundColor then it’s working fine
summary two functions :)
window.getComputedStyle(element).backgroundColor
element.style.backgroundColor
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
