Pat
Pat

Reputation: 613

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.

Upvotes: 0

Views: 4271

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

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>

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

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>

Upvotes: 1

Related Questions