Question

I have a table that has rows that are tagged by a class. These rows should be zebra striped. The caveat is that they are not always consecutive.

I have tried matching by table and class name but the end result is always incorrect. What is happening is that the striping will be applied at the table level and then enabled only on the rows with the class.

What do I have to change to make this work like I intend?

Script

function FormatTable()
{
   $("#TableId .arbitrarySelector:nth-child(2n+1)" ).addClass('anotherEquallySpecialRow')
}

HTML

<table id="TableId" onclick="FormatTable()">
    <tr class="arbitrarySelector">
        <td><div class="space">Should be Changed and is</div></td>
    </tr>
    <tr class="arbitrarySelector">
        <td><div class="space">Should Not be Changed and is Not</div></td>
    </tr>
    <tr class="arbitrarySelector">
        <td><div class="space">Should be Changed and is</div></td>
    </tr>
    <tr>
        <td><div class="space"></div></td>
    </tr>
    <tr class="arbitrarySelector">
        <td><div class="space">Should NOT be changed but is</div></td>
    </tr>
    <tr>
        <td><div class="space"></div></td>
    </tr>
    <tr class="arbitrarySelector">
        <td><div class="space">Should be Changed and is</div></td>
    </tr>
    <tr>
        <td><div class="space"></div></td>
    </tr>
    <tr>
        <td><div class="space"></div></td>
    </tr>
    <tr class="arbitrarySelector">
        <td><div class="space">Should Not be Changed and is Not</div></td>
    </tr>
    <tr class="arbitrarySelector">
        <td><div class="space">Should be Changed and is</div></td>
    </tr>
    <tr class="arbitrarySelector">
        <td><div class="space">Should Not be Changed and is Not</div></td>
    </tr>
</table>
Was it helpful?

Solution

You might be making this too difficult. If you want to do zebra striping, why not just use something like the :odd selector and change the class depending. Something like this...

// Add zebra striping.
$('.arbitrarySelector:odd').addClass('zebra');

And then the CSS would be something like...

.zebra 
{
    background-color: #dddddd;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top