Reputation: 1157
I have a table and I want the first 3 TD
to have a different background color. I figured I could use the :lt() Selector
for this, but at this point I am only able to give the first 3 TD
the same yellow background color.
I use the following code:
<script>
$( "td:lt(3)" ).css( "backgroundColor", "yellow" );
</script>
But as mentioned above, I want al 3 TD
to have different background colors. How can I give the first TD
a yellow background, the second TD
a blue background and the third TD
a red background?
Thanks
Upvotes: 1
Views: 79
Reputation: 665574
I think you're looking for a simple
var tds = $("td");
tds.eq(0).css( "backgroundColor", "yellow" );
tds.eq(1).css( "backgroundColor", "blue" );
tds.eq(2).css( "backgroundColor", "red" );
You can also use :eq()
as a selector if you want to repeat the td
selection (which you shouldn't, though).
Alternatively, this will do it:
$( "td:lt(3)" ).css( "backgroundColor", function(i) {
return ["yellow", "blue", "red"][i];
});
Upvotes: 2
Reputation: 1547
Use :nth-child
selector:
<script>
$('td:lt(3):nth-child(1)').css('backgroundColor','yellow');
$('td:lt(3):nth-child(2)').css('backgroundColor','blue');
$('td:lt(3):nth-child(3)').css('backgroundColor','red');
</script>
Demo: http://jsfiddle.net/6u4Yu/3/
Upvotes: 2
Reputation: 519
Sounds like a good case for :nth-child... and :first-child since you want only the top row.
Fiddle: http://jsfiddle.net/8GUTp/2/
<script>
$( "tr:first-child td:nth-child(1)" ).css( "backgroundColor", "yellow" );
$( "tr:first-child td:nth-child(2)" ).css( "backgroundColor", "blue" );
$( "tr:first-child td:nth-child(3)" ).css( "backgroundColor", "red" );
</script>
Upvotes: 2