Cameron
Cameron

Reputation: 28803

jquery: Change the background-colour of a column if its header has a class

I have the following jQuery that I'm trying to use to change the background colour of a column where its header has a class.

So for example:

$('th').each(function (i) {

            if ($(this).hasClass('headerSortUp') || $(this).hasClass('headerSortDown')) {
                sortIndex = $(this).index();
            }
            $('tr').each(function () {
                $('td:eq(' + sortIndex + ')').css('background-color', 'orange');
            });

        });

So if I had a table like:

<table>
<tr>
    <th class="headerSortDown">Header</th>
    <th>Header</th>
    <th>Header</th>
    <th>Header</th>
    <th>Header</th>
</tr>
<tr>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
</tr>
<tr>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
</tr>
<tr>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
</tr>
</table>

So in this example the whole first column should have a bg of orange. However it's not working... Any ideas what I have done wrong? Thanks

Upvotes: 0

Views: 739

Answers (4)

Alnitak
Alnitak

Reputation: 339816

There's no need to iterate over the <th> elements - a selector can pick out just the ones with the right classes.

You can then use .index() to find their column value, and :nth-child() to select every <td> in that column in one go:

$('.headerSortUp, .headerSortDown').each(function() {
    var n = $(this).index() + 1;
    $('td:nth-child(' + n + ')').css('background-color', 'orange');
});

Working demo at http://jsfiddle.net/jNsF4/

[I note also that the original code has a logic error - the code to change the colours should be inside the if { ... } block, not outside it].

Upvotes: 1

Ryan
Ryan

Reputation: 3815

There's probably a better selector that causes lesser iterations

var sortIndex;

$('th').each(function (i) {

            if ($(this).hasClass('headerSortUp') || $(this).hasClass('headerSortDown')) {
                sortIndex = $(this).index();
            }
    });


$('td:nth-child(' +sortIndex+1+')').css('background-color', 'orange');

You can check the fiddle here http://jsfiddle.net/ryan_s/nZr9G/

Upvotes: 0

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

Try changing sortIndex = $(this).index(); to sortIndex =i; and
$('td:eq(' + sortIndex + ')').css('background-color', 'orange'); to

$('td:eq(' + sortIndex + ')',$(this)).css('background-color', 'orange'); to select td 's withing the tr

Upvotes: 1

Manuel van Rijn
Manuel van Rijn

Reputation: 10305

you forgot to specify the context

$('td:eq(' + sortIndex + ')', this).css('background-color', 'orange');

Upvotes: 1

Related Questions