Pat Pat - 5 months ago 90
Javascript Question

jQuery add thead to the table

I am using

MyFaces Trinidad JSF
framework and it creates tr:table as follows:

<table id="myTable">
<tbody>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>


I need the below one to implement scrollable header. So I am trying to convert them using
jQuery


<table id="myTable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>


I have tried this and this answers, but none of them solves my problem.

Answer

Wrap first row with thead and append at the beginning of the table

$('#myTable tbody tr:first') // get first row
  //.detach() // remove from table, it's optional to detach
  .wrap('<thead/>') // wrap with tbody
  .parent() // get tbody 
  .prependTo('#myTable') // append at the beginning
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tbody>
  <tr><th>1</th><th>2</th><th>3</th><th>4</th></tr>
  <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
  <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
  <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
  <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
  <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
</tbody>
</table>