Select every second row of the visible table.

I have a table displaying a tree structure (super- and subcategories). When a user clicks on a supercategory, the display property of the child elements is sent.

Now I want to add an alternating background color for every second row of the table, but, of course, only consider those that are currently visible. The following is a simplified structure example:

<table>
    <tr data-level="0"><td>Super 1</td></tr>
    <tr class="hide" data-level="1"><td>Sub 1</td></tr>
    <tr data-level="0"><td>Super 2</td></tr>
    <tr class="hide" data-level="1"><td>Sub 2</td></tr>
    <tr class="hide" data-level="1"><td>Sub 3</td></tr>
    <tr class="hide" data-level="1"><td>Sub 4</td></tr>
</table>

When the user clicks on the Super 2 element, the hide classes are removed from the child elements.

I tried several selectors, for example:

/* Ugly result (dosn't recognize that elements are hidden) */
tr:nth-child(2n)
{
    background-color: grey;
}

/* Doesn't work at all */
tr:visible:nth-child(2n)
{
    background-color: grey;
}

/* Not what I inteded to do */
tr:not(.hide):nth-child(2n)
{
    background-color: grey;
}

I hope I understand what I want to do.

Is this possible with CSS or should I write a JS script that recounts even and odd lines whenever something changes? Thanks in advance for any tips!

+5
3

jQuery :

$('tr').removeClass('alternate')​
$('tr:not(.hide):odd').addClass('alternate')​

jsFiddle

+1

, hide onclick.
IE: "".

.show tr:nth-child(odd)    { background-color:#eee; }
.show tr:nth-child(even)   { background-color:#fff; }

:
exaustion, , .

tr.show:nth-child(odd)    { background-color:#eee; }
tr.show:nth-child(even)   { background-color:#fff; }
+2

Updated and faster way to complete the task:

$('tr').removeClass();
$('tr:not(:hidden)').filter(':odd').addClass('odd');

Then you can style these odd lines in CSS with .odd {}

0
source

All Articles