Cannot get background style using javascript

Viewed 454

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

2 Answers

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>

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>

Related