3

I'm trying to get the simple hex code value of the test div. I've followed the exact same principle as with this post, although I'm not getting it. What should be logged into the console is the hex code #0ff0ff

var test = document.getElementById('test'),
    window.getComputedStyle(test);

console.log(style.getPropertyValue('background'));
#test {
  background: #0ff0ff;
}
<div id='test'>test</div>

Any ideas where I'm going wrong? Thanks for any help here

Evgeny Klimenchenko
  • 1,184
  • 1
  • 6
  • 15
user8758206
  • 2,106
  • 4
  • 22
  • 45

2 Answers2

2

Adding RGB to HEX CODE from theblackgigant's answer. RGB to Hex Code Erick Petrucelli's Solution

var test = document.getElementById("test");

//Get the color Code
  var theCSSprop = window.getComputedStyle(test, null).getPropertyValue("background-color");
  
//Most browsers seem to return the RGB value
//Function to Convert RGB to Hex Code
function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

//Output
console.log(rgb2hex(theCSSprop));
#test {
  background: #0ff0ff;
}
<div id='test'>test</div>
1

You are not storing the value of window.getComputedStyle(test) inside the variable style.

Be aware that getPropertyValue('background-color') returns a RGB value not a HEX code.

var test = document.getElementById('test');

var style = window.getComputedStyle(test);

console.log(style.getPropertyValue('background-color'));
#test {
  background: #0ff0ff;
}
<div id='test'>test</div>
Reyno
  • 6,119
  • 18
  • 27
  • 4
    RGB or non-RGB is totally up to the browser. (Modern ones return RGB/A but who knows one day one might decide to return HEX/A) @user875 – Roko C. Buljan Jul 02 '20 at 10:04
  • Cool, didn't know that, i thought it was always RGB – Reyno Jul 02 '20 at 10:06
  • Indeed :) regarding the returned values and getComputedStyle: https://stackoverflow.com/a/60689673/383904 - In case OP was after comparing colors... – Roko C. Buljan Jul 02 '20 at 10:09