Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get background style using javascript

Tags:

javascript

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

like image 635
user8758206 Avatar asked Feb 13 '26 12:02

user8758206


1 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>
like image 186
benjamintemitope Avatar answered Feb 16 '26 00:02

benjamintemitope



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!