1

I'm looking to loop through the rows of a table and checking to see what color they have for background. This is what I have so far:

var TheColor = "";

$('#MyTable tr').each(function () {
    TheColor = "";
    TheColor = $(this).attr('background-color');
    alert(TheColor);
});

When the loops unfolds, all I'm getting is "undefined" and I'm not seeing why. However, when I write TheColor = $(this).html(); I'm getting the expected output.

Thanks for suggestions.

janhartmann
  • 14,713
  • 15
  • 82
  • 138
frenchie
  • 51,731
  • 109
  • 304
  • 510
  • Does your "tr" really have a "background-color" attribute? You might should be looking at a style attribute with that property. – janhartmann Mar 21 '11 at 18:42

2 Answers2

5

You need to select it like:

$(this).css('background-color');

Since the attribute you are looking for is actually a style property (style="background-color: red").

janhartmann
  • 14,713
  • 15
  • 82
  • 138
  • Indeed. `background-color` isn't an attribute on the `tr` element, it's a piece of style information. @frenchie: More: http://api.jquery.com/css/#css1 – T.J. Crowder Mar 21 '11 at 18:46
  • ok, this works. However, it's returning the values in the form of rgb(...). Do you know why it's not returning the data in the format of #FDFEGG ? – frenchie Mar 21 '11 at 18:47
  • See: http://stackoverflow.com/questions/638948/background-color-hex-to-javascript-variable-jquery – janhartmann Mar 21 '11 at 18:49
0
$('#MyTable tr').map(function(item){ return item.css('background-color'); })

This will return an array of background colors with each element in the array representing the background color from the table.

Sergei Golos
  • 4,342
  • 1
  • 18
  • 21