How to extract r, g, b, a values from CSS color?

Misha Moroshko picture Misha Moroshko · Sep 20, 2010 · Viewed 13.4k times · Source

What would be the easiest way to transform

$('#my_element').css('backgroundColor')

to object like this:

{ r: red_value, g: green_value, b: blue_value, a: alpha_value }

?

Answer

user372551 picture user372551 · Sep 20, 2010
var c = $('body').css('background-color');
var rgb = c.replace(/^(rgb|rgba)\(/,'').replace(/\)$/,'').replace(/\s/g,'').split(',');

for(var i in rgb) {
  console.log(rgb[i]);
}

Try it here http://jsbin.com/uhawa4

Edit :

var c = $('body').css('background-color');
var rgb = c.replace(/^rgba?\(|\s+|\)$/g,'').split(',');

for(var i in rgb) {
  console.log(rgb[i]);
}

or even simpler way, just aiming at numbers

var c = 'rgba(60,4,2,6)';
var rgb = c.match(/\d+/g);

for(var i in rgb) {
  console.log(rgb[i]);
}