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

laukok picture laukok · May 14, 2011 · Viewed 134k times · Source

How do I get the background color code of an element?

What I want

#f5b405

Answer

Hussein picture Hussein · May 14, 2011

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/