[jquery] Jquery assiging class to th in a table

I am trying to assign class to table headers. I am trying to read class names of td's and assign it to related th header. Any help would be appreciated.

<table >   <tr>     <th>hdrcol1</th>     <th>hdrcol2</th>     <th>hdrcol3</th>  </tr>  <tr>     <td class="title">col1</td>     <td class="desc">col2</td>     <td class="addclr">col3</td>  </tr>  <tr>     <td class="title">col11</td>     <td class="desc">col22</td>     <td class="addclr">co33</td>  </tr> </table>  $('table tbody tr td').each(function(index){      if($('tr th').eq(index).attr('class') != ''){         //put this class on the current td         $(this).addClass($('thead tr th').eq(index).attr('class'));     } }); 

What I tried in fiddle id here

This question is related to jquery table addclass

The answer is


You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle