Oromis Oromis - 3 months ago 19
CSS Question

Selecting every second visible table row

I have a table displaying a tree structure (Super- and Subcategories). When the user clicks on a supercategory, the display property of the childs is toggeled.

Now I want to add an alternating background color on every second table row - but of course taking only those into account which are currently visible. Below is a simplified example of the structure:

<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, e.g.:

/* 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 got clear on what i want to do.

Is that possible with CSS or should I write a JS script that recalulates the even and odd rows whenever anything changes?
Thanks in advance for any hints!

Answer

This jQuery snippet will do the job:

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

Play with it on the jsFiddle