Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Selecting Table Columns by Index

I have a table MyTable and I want to select column i using a loop and test if column i has a certain css class.

I tried this:

thestop = 4; // simplified for clarity

for (i = 0; i < thestop; i++){
   if ( $('#MyTable .th').eq(i).hasClass('MyClass') )
      { $(this).width('60'); }
}

For sure there are several problems with this and I can't seem to figure it out. Any ideas welcome!

Thanks.

like image 470
frenchie Avatar asked Dec 05 '25 22:12

frenchie


2 Answers

$('#MyTable th.MyClass').each(function(i) {
    $(this).width( arr[i] );
}); 

where arr is the array containing the widths.

like image 127
Šime Vidas Avatar answered Dec 08 '25 11:12

Šime Vidas


The thing I spotted right off is that .th will find elemets with the class th, not <th> elements (use plain th for that). Also, I'm not sure that $(this) is referring to the selected element in this case - I think it only behaves like that in .each(function() {}) functions...

Anyways, I think you can do this in a pretty elegant one-liner:

thestop = 4;
$('#MyTable th.MyClass:lt('+thestop+')').width('60px');

This'll find all the <th>s in your table that have an index of less than thestop (using the jQuery :lt selector), and set their widths right there. And if you actually did want things with the class 'th', just put that leading dot back in.

Hope that helps!

like image 37
Xavier Holt Avatar answered Dec 08 '25 10:12

Xavier Holt