How to get the background color code of an element in hex?

Check example link below and click on the div to get the color value in hex.

var color = '';
$('div').click(function() {
  var x = $(this).css('backgroundColor');
  hexc(x);
  console.log(color);
})

function hexc(colorval) {
  var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
  delete(parts[0]);
  for (var i = 1; i <= 3; ++i) {
    parts[i] = parseInt(parts[i]).toString(16);
    if (parts[i].length == 1) parts[i] = '0' + parts[i];
  }
  color = '#' + parts.join('');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='div' style='background-color: #f5b405'>Click me!</div>

Check working example at http://jsfiddle.net/DCaQb/


There's a bit of a hack for this, since the HTML5 canvas is required to parse color values when certain properties like strokeStyle and fillStyle are set:

var ctx = document.createElement('canvas').getContext('2d');
ctx.strokeStyle = 'rgb(64, 128, 192)';
var hexColor = ctx.strokeStyle;

You have the color you just need to convert it into the format you want.

Here's a script that should do the trick: http://www.phpied.com/rgb-color-parser-in-javascript/


function getBackgroundColor($dom) {
    var bgColor = "";
    while ($dom[0].tagName.toLowerCase() != "html") {
      bgColor = $dom.css("background-color");
      if (bgColor != "rgba(0, 0, 0, 0)" && bgColor != "transparent") {
        break;
      }
      $dom = $dom.parent();
    }
    return bgColor;
  }

working properly under Chrome and Firefox