Matthew Grima
Matthew Grima

Reputation: 1523

HTML Tables - can I have an additional tbody before the thead?

I need add to some elements on top of a table in line with the columns of the said table.

This table contains a <thead> (which is required due to jquery.tablesorter plugin). I assumed that if I put another <tbody> on top of the <thead> I would be able to keep these elements in line with the rest of the columns, but both chrome and firefox render every <tbody> below the <thead>.

Example:

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

Although I understand this, I still need to find a way to have these elements stay in line with specific columns.

Upvotes: 3

Views: 5408

Answers (4)

rgvcorley
rgvcorley

Reputation: 2923

You can use multiple rows in <thead> like this:-

<table>

   <thead>

     <tr> <td>1</td> <td>1</td> </tr>

     <tr> <td>head</td> <td>head</td> </tr>

   </thead>

</table>

Upvotes: 6

Edward Ruchevits
Edward Ruchevits

Reputation: 6696

Correct table structure is:

<table>
    <thead>
        <tr>
            <th></th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th></th>
            <th></th>
        </tr>
    </tfoot>
</table>

<thead> will always be on the top and <tfoot> will always be at the bottom.


Using jQuery you can swap <thead> and <tbody> content by:

$(document).ready(function() {
    $('#myTrigger').click(function() {
        var top = $('thead').html();
        var mid = $('tbody').html();
        $('thead').html(mid);
        $('tbody').html(top);
    });
});

Upvotes: 1

Michael Durrant
Michael Durrant

Reputation: 96484

I recommend that you use an id (#) marker to identify that part that you want the js to work off and have the js use that id.

With that, have the thead first and the tbody last.

The variations you are describing may work - in the browser you using now, on the OS you are ok - and may be compliant a certain version of the HTML spec- but putting things in an unusual order is (in my expereince) just the kind of thing to not work, or work the same, everywhere and to eventually be the cause of much frustration, especially as the site grows in complexity.

Upvotes: 1

Marcelo Assis
Marcelo Assis

Reputation: 5194

One solution is to use another table inside one tr, in your thead. Althought, this is a totally ugly solution.

You can also place a div above your table using CSS.

Upvotes: 0

Related Questions