views:

111

answers:

2
$('.table tbody td:eq(3)').addClass('col4');

..works, but only selects the first cell, not all cells in the column.

+12  A: 

Try:

$(".table tbody td:nth-child(4)").addClass("col4");

Note: I've put 4 here because :eq(n) is zero-based and :nth-child(n) is one-based.

You've stumbled on the key difference between the two. eq(3) will return exactly one element, the 4th from the entire set. Much like how :first only returns one element (max) whereas :first-child can return many.

cletus
Perrrrrrrrrfect! :) (Sorry, SO won't allow less than 15 chars)
Nimbuz
This also demonstrates why jQuery's `:eq` selector should be viewed with suspicion. It applies not to the selector-part in context like every other :psuedo-class selector, but to the selector in its entirity. Since it is not a standard CSS selector it also forces use of the Sizzle library instead of the fast `querySelectorAll` implementation in newer browsers. Where you need this functionality, avoid the `:eq` selector; use `.eq()` on the results instead.
bobince
A: 

You could also use the <col> element to style whole columns instead of having to apply styles to all <td>s in that column.

http://www.w3.org/TR/html401/struct/tables.html#h-11.2.4.2

Chetan Sastry
I don't think you can do much with <col>, it doesn't allow CSS styling I guess?
Nimbuz
It does, but only allows a few styles. http://www.quirksmode.org/css/columns.html
Chetan Sastry