简体   繁体   中英

Move first row of a HTML table under a thead tag using JavaScript

I have a html table generated by BIRT as follow:

<table id="myTableID">
    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>

    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>

    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>
</table>

I want to write a JavaScript code that reads this table and re-writes it in the following form: getting the first row of the table in a <thead> tag, and the rest of the table in the <tbody> tag:

<table id="myTableID">
    <thead>
        <tr>
            <th></th>
            <th></th>
            <th></th> 
        </tr>
    </thead>

    <tbody>
        <tr>
            <th></th>
            <th></th>
            <th></th>
        </tr>

        <tr>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </tbody>    
</table>

I have a basic knowledge about the JavaScript, but I have no clue how to proceed with such case. Please any help?

  1. Use prependTo() to insert the thead element
  2. Use append() to insert the first tr inside the thead

 $('<thead></thead>').prependTo('#myTableID').append($('#myTableID tr:first')); console.log($('#myTableID')[0].outerHTML); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <table id="myTableID"> <tr> <th></th> <th></th> <th></th> </tr> <tr> <th></th> <th></th> <th></th> </tr> <tr> <th></th> <th></th> <th></th> </tr> </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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM