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.
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>
you can use
// append the first row to thead and prepend thead to #mytable
$('<thead></thead>').append($('tbody > tr:nth-child(1)')).prependTo('#myTable');
// remove the first row from tbody
$('#myTable > tbody > tr:nth-child(1)').remove();
// append the first row to thead and prepend thead to #mytable $('<thead></thead>').append($('tbody > tr:nth-child(1)')).prependTo('#myTable'); // remove the first row from tbody $('#myTable > tbody > tr:nth-child(1)').remove();
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.