Select all cells in the nth column using jQuery

How to select all cells in the nth column of a normal html table. Ive tried this but didn't work:

$('table#foo tbody td:nth-child(3)').each(function (index) { $(this).addClass('hover'); }); 

UPDATE: Heres jsfiddle broken code: http://jsfiddle.net/Claudius/D5KMq/

+4
source share
3 answers

There is no need to use each for this.

 $('table#foo tbody td:nth-child(3)').addClass('hover'); 

Other than that, there is nothing wrong with the code. The problem should be somewhere else.

+8
source

Your actual problem (not obvious in the original question, but there in the fiddle) is that .index() returns a value based on zero, but :nth-child() requires a one-time value.

+6
source
 $('table#foo tbody td:nth-child(3)').addClass('hover'); 

Use this script (note that using: nth-child is the selector index of each child that matches, starting at 1)

 $(".legendvalue", ".stmatst_legends").hover(function() { var index = $('.legendvalue').index($(this)); $('table#stmstat tbody td:nth-child(' + (index + 1) + ')').addClass('hover'); }, function() { //remove hover }); 
0
source

All Articles