Norbert Norbert - 1 month ago 8
jQuery Question

Append <th> Class to <td> in the Same Column

I've been searching all over the net for hours now but I still can't figure this out.

<table>
<tr>
<th class="name">Name</th>
<th class="age">Age</th>
<th class="nick">Nick</th>
</tr>

<tr>
<td>John</td>
<td>30</td>
<td>Johnny</td>
</tr>

<tr>
<td>Robert</td>
<td>35</td>
<td>Bob</td>
</tr>
</table>


Is there any way to append the classes from those headers to the TD tags in the same column?

Answer

I would do it this way:

$("table th").each(function(i, val) {
  var th = $(this);
  var selector = "td:nth-child(" + (i+1) + ")";
  th.parent().siblings().find(selector).attr("class", th.attr("class"));
});

It uses the :nth-child selector to effectively get the same <td> in the same column. It breaks down if you use rowspan/colspan elements however.

Note: you have to add one to the index because the index on each() is zero-based but :nth-child() is one-based.

Also, you can't use the :eq selector in this context as it only matches a single element.