Search code examples
jqueryhtml-tabletraversal

Jquery append .header to thead tr th


Currently there is a tr.header td but I need it to be in the empty thead tr th

$("#new table tr.Header td").each(function(){
  $(this).appendTo("thead tr th");
});

This works actually but the problem I have is that multiple tables exist in the DOM. I don't need every single header in all the headers. I just need each table's tr.header to get appended to the thead tr th. Header 1 will get appended to the table 1's thead...and so on.

How can I achieve this?

Current result is:

<table>
<thead>
 <tr>
  <th>Header 1 Header 2 Header 3 Header 4</th>
 </tr>
</thead>
<tbody><tr><td>
   Row 1
  </td></tr> 
 <tr><td>
   Row 2
  </td></tr> 
 <tr><td>
   Row 3
  </td></tr>
</tbody> 
</table> 

<table>
<thead>
 <tr>
  <th>Header 1 Header 2 Header 3 Header 4</th>
 </tr>
</thead>
<tbody><tr><td>
   Row 1
  </td></tr> 
 <tr><td>
   Row 2
  </td></tr> 
 <tr><td>
   Row 3
  </td></tr>
</tbody> 
</table> 

<table>
<thead>
 <tr>
  <th>Header 1 Header 2 Header 3 Header 4</th>
 </tr>
</thead>
<tbody><tr><td>
   Row 1
  </td></tr> 
 <tr><td>
   Row 2
  </td></tr> 
 <tr><td>
   Row 3
  </td></tr>
</tbody> 
</table> 

<table>
<thead>
 <tr>
  <th>Header 1 Header 2 Header 3 Header 4</th>
 </tr>
</thead>
<tbody><tr><td>
   Row 1
  </td></tr> 
 <tr><td>
   Row 2
  </td></tr> 
 <tr><td>
   Row 3
  </td></tr>
</tbody> 
</table> 

Without any jQuery the tables all appear like this:

<table>
<thead>
 <tr>
  <th></th>
 </tr>
</thead>
<tbody><tr class="Header"><td>
   Header 1
  </td></tr>
  <tr><td>
   Row 1
  </td></tr> 
 <tr><td>
   Row 2
  </td></tr> 
 <tr><td>
   Row 3
  </td></tr>
</tbody> 
</table> 

Solution

  • I must say that it's one of the most unusual things that people asks here, but here you go:

    $("table tr.Header td").each(function(){
      $(this).appendTo($(this).closest('table').find('thead tr th'));
    });