0

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>

1 Answers1

0

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

Dharman
  • 30,962
  • 25
  • 85
  • 135