1

I tried to apply color to rows of a table using the following code. It doesn't work, but I don't understand why. Could someone explain why or point me in the right direction?

HTML:

<table id="tblSample" border="1" cellpadding="0" cellspacing="0" width="300px">
    <tr>
        <td>1</td>
        <td>1</td>
    </tr>
    <tr>
        <td>2</td>
        <td>2</td>
    </tr>
</table>

JQuery:

$("#tblSample > tr").css("background-color", "gray");
Temani Afif
  • 211,628
  • 17
  • 234
  • 311
Sukhjeevan
  • 3,308
  • 7
  • 43
  • 86

3 Answers3

6

You're missing the elusive tbody element.

http://jsfiddle.net/m7HTt/

You can do this:

$("#tblSample > tbody > tr").css("background-color", "gray");

or this:

$("#tblSample tr").css("background-color", "gray");
Community
  • 1
  • 1
thirtydot
  • 217,782
  • 47
  • 385
  • 346
1

If you are looking to do alternating row colors you can do something as simple as this as well.

$("#tblSample tr:even").css("background-color", "gray");
Mike Geise
  • 825
  • 7
  • 14
  • Thanks Mike! yr solution also really helpful for me.i didn't know before we can apply alternate row color in this way. – Sukhjeevan Feb 26 '11 at 06:29
-1

Try it

$("#tblSample  tr").css("background-color", "gray");

or

$("#tblSample tr td").css("background-color", "gray");
Santosh Linkha
  • 13,916
  • 17
  • 75
  • 114
Deepak
  • 6,807
  • 3
  • 22
  • 26