Reputation: 32721
I have the following table.
<table>
<tr>
<td>
<img src="images/kategoriimg1.jpg" />
<p>Forskerspiren</p>
</td>
<td>
<img src="images/kategoriimg2.jpg" />
<p>Mangfold i naturen</p>
</td>
<td>
<img src="images/kategoriimg3.jpg" />
<p>Kropp og helse</p>
</td>
<td>
<img src="images/kategoriimg4.jpg" />
<p>Verdensrommet</p>
</td>
</tr>
<tr>
<td>
<img src="images/kategoriimg5.jpg" />
<p>Fenomener og
stoffer</p>
</td>
<td>
<img src="images/kategoriimg6.jpg" />
<p>bla</p>
</td>
<td>
<img src="images/kategoriimg7.jpg" />
<p>bla</p>
</td>
<td>
<img src="images/kategoriimg8.jpg" />
<p>bla</p>
</td>
</tr>
.....
.....
// more tr and td with images like above
....
</table>
Now I want to add class grid_3, alpha first to all first tds, grid_3 middle to all second and third tds and middle and grid_3 omega last to all forth tds with jquery like this.
<table>
<tr>
<td class="grid_3 alpha first">
<img src="images/kategoriimg1.jpg" />
<p>Forskerspiren</p>
</td>
<td class="grid_3 middle">
<img src="images/kategoriimg2.jpg" />
<p>Mangfold i naturen</p>
</td>
<td class="grid_3 middle">
<img src="images/kategoriimg3.jpg" />
<p>Kropp og helse</p>
</td>
<td class="grid_3 omega last">
<img src="images/kategoriimg4.jpg" />
<p>Verdensrommet</p>
</td>
</tr>
<tr>
<td class="grid_3 alpha first">
<img src="images/kategoriimg5.jpg" />
<p>Forskerspiren</p>
</td>
<td class="grid_3 middle">
<img src="images/kategoriimg6.jpg" />
<p>Mangfold i naturen</p>
</td>
<td class="grid_3 middle">
<img src="images/kategoriimg7.jpg" />
<p>Kropp og helse</p>
</td>
<td class="grid_3 omega last">
<img src="images/kategoriimg8.jpg" />
<p>Verdensrommet</p>
</td>
</tr>
....
....
</table>
Upvotes: 0
Views: 299
Reputation: 29831
var $td = $('td').addClass('grid_3');
$td.filter(':not(:first-child,:last-child)').addClass('middle');
$td.filter(':first-child').addClass('first alpha');
$td.filter(':last-child').addClass('last omega');
Upvotes: 3
Reputation: 6866
Try this...
$("table tr").each(function(){
$(this).find("td:eq(0)").attr("class","grid_3 alpha first");
$(this).find("td:eq(1),td:eq(2)").attr("class","grid_3 middle");
$(this).find("td:eq(3)").attr("class","grid_3 omega last");
});
Upvotes: 3
Reputation: 24292
$('table tr td').addClass('grid_3');
$('table tr td:nth-child(0)').addClass('alpha first');
$('table tr td:nth-child(1)').addClass('middle');
$('table tr td:nth-child(2)').addClass('middle');
$('table tr td:nth-child(3)').addClass('omega last');
Upvotes: 0
Reputation: 26997
Don't even use jQuery :). Use the CSS3 nth-child selectors:
http://www.w3.org/TR/css3-selectors/
Upvotes: 0