1

I have a yellow button.

When I click the button, I want to get the button's color.

I tried this:

<html>

<head>
  <style rel="stylesheet">
    .A {
      background-color: #ffff00
    }
  </style>
  <script>
    function clicked() {
      console.log(document.getElementById("A1").style.backgroundColor);
    }
  </script>
</head>

<body>
  <input type="button" id="A1" class="A" value="1" onclick="clicked()">
</body>

</html>

then I got nothing.

How can I get 'yellow' or '#ffff00'?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Hoseong Jeon
  • 1,240
  • 2
  • 12
  • 20
  • You are probably looking for [`getComputedStyle`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle). – Alexander Nied Nov 25 '18 at 07:05
  • 1
    Possible duplicate of [How to get \`background-color\` property value in Javascript?](https://stackoverflow.com/questions/25238153/how-to-get-background-color-property-value-in-javascript) – Mohammad Nov 25 '18 at 07:57

3 Answers3

3

You can try to use getComputedStyle method to get the button style:

function clicked() {
  var button = document.getElementById("A1");
  var style = getComputedStyle(button);
  
  console.log(style['background-color']);
}
.A { background-color: #ffff00 }
<input type="button" id="A1" class="A" value="1" onclick="clicked()">
Tân
  • 1
  • 15
  • 56
  • 102
0

Your CSS

<style rel="stylesheet">
    .A { background-color: #ffff00 }
</style>

You must write this way

<input type="button" id="A1" class="A" value="1" onclick="clicked()">

    <script>
    function clicked() {
    const element = document.getElementById('A1');
    const style = getComputedStyle(element);
        console.log(style.backgroundColor);
    }
</script>
0

You have to use window.getComputedStyle().

The window.getComputedStyle() method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object or by simply indexing with CSS property names.

Then you have to convert the rgb value to hex.

You can try the following way:

function clicked(el) {
  var bg_color = window.getComputedStyle(el, null).backgroundColor;
  bg_color = bg_color.match(/\d+/g);
  console.log(rgbToHex(bg_color));
}
    
function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(rgb) {
  return "#" + componentToHex(+rgb[0]) + componentToHex(+rgb[1]) + componentToHex(+rgb[2]);
}
.A { background-color: #ffff00 }
<input type="button" id="A1" class="A" value="1" onclick="clicked(this)">
Mamun
  • 66,969
  • 9
  • 47
  • 59