Norbert Norbert - 3 years ago 111
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.

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



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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download