Oromis Oromis - 2 months ago 6x
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:

<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>

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) */
background-color: grey;

/* Doesn't work at all */
background-color: grey;

/* Not what I inteded to do */
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!


This jQuery snippet will do the job:


Play with it on the jsFiddle