crjunk
crjunk

Reputation: 969

Alternate Table Row and Column Color with jQuery

I'm trying to use the following code to alternate the rows and columns of my table.

<script>
  $(document).ready(function()
  {
    $("table#id2 td:even").css("background-color", "LightGray");
    $("table#id2 tr:even").css("background-color", "LightBlue");
    $("table#id2 tr:odd").css("background-color", "LightYellow");
  });
</script>

When I use this, my 2 column table looks something like this:

Gray Blue
Gray Yellow
Gray Blue
Gray Yellow

I'd like my table to look like this:

Gray Blue
Yellow Yellow
Gray Blue
Yellow Yellow

Is this possible using the td:even, tr:odd, etc.. ?

Upvotes: 0

Views: 4712

Answers (2)

Stephen Fischer
Stephen Fischer

Reputation: 2546

You have to specify the background color on tr:odd td

$("table#id2 td:even").css("background-color", "LightGray");
$("table#id2 tr:even").css("background-color", "LightBlue");
$("table#id2 tr:odd td").css("background-color", "LightYellow");

Here's a fiddle showing a solution: http://jsfiddle.net/mEFWm/

Upvotes: 1

karthikr
karthikr

Reputation: 99620

Basically, apply the color only for the odd rows Try: 

<script>
  $(document).ready(function()
  {
    $("table#id2 td:even").css("background-color", "LightGray");
    $("table#id2 tr:even").css("background-color", "LightBlue");
    $("table#id2 tr:odd td").css("background-color", "LightYellow");
  });
</script>

fiddle here

Upvotes: 2

Related Questions