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.
$('#MyTable th.MyClass').each(function(i) {
$(this).width( arr[i] );
});
where arr is the array containing the widths.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With