Jon
Jon

Reputation: 4945

Setting table header alignment based on first row alignment

I would like to set the alignment of a table's headers based on the alignment of the first <td> in each respective column.

<table>
    <thead>
        <tr>
            <th>First Column</th>
            <th>Second Column</th>
            <th>Third Column</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Value One</td>
            <td align="right">Value Two</td>
            <td align="center">Value Three</td>
        </tr>
        <!-- more rows -->
    </tbody>
</table>

In this example, the second <th> would get aligned to the right and the third <th> would get centered. The first <th> would not be affected. Any suggestions/examples of how to accomplish this with jQuery would be very appreciated.


Based on InfernalBadger's answer, this is what I ended up using. Turns out I needed to take into account the CSS text-align property as well as handling multiple tables.

function alignGridHeaders() {
    $('table.grid thead th').each(function (index) {
        var cell = $(this).parents('table:first').children('tbody tr:first td').eq(index);
        var alignment = cell.css('text-align');
        if (!alignment)
            alignment = cell.attr('align');
        if (alignment)
            $(this).css('text-align', alignment);
    });
}

Upvotes: 2

Views: 2461

Answers (3)

Phillip Gooch
Phillip Gooch

Reputation: 577

Another, probably far less efficient, method. It does have the advantage of making blank or no align instructions left, but thats not much.

function toprowalign(){
    var pos = 1;
    $('table tr:nth-child(1) ').children('td').each(function(){
        var align = $(this).attr('align');
        if(align==''){align='left';}
        $('table tr th:nth-child('+pos+') ').attr('align',align);
        pos++;
    })
}

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

JSFiddle Example

$('#myTable th').each(function(index) {
    var alignment = $('#myTable tbody  tr:first td').eq(index).attr('align');
    if (alignment )
        $(this).css('text-align', alignment);   
});

I gave the table an ID of myTable for this example.

Upvotes: 3

Hacknightly
Hacknightly

Reputation: 5144

You'll probably want to use the jQuery eq function. This will allow you to simply pass in the number of which element you'd like to modify. In your case, it would probably look something like this

$(document).ready(function(){

  $('#trID li').eq(2).css('align', 'right')
  $('#trID li').eq(3).css('align', 'center')

});

Hope this helps a bit!

Upvotes: 0

Related Questions