Selecting elements between other elements
OK, so I'm doing some simple zebra-striping on a table... or so I thought. The problem is that the table is set up in a kind of weird way, like this:
- <table class='striped' ...>
- <tr><th colspan='4'>Section Title</th></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- <tr><th colspan='4'>Section Title</th></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- <tr><th colspan='4'>Section Title</th></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- <tr> <td>Data 1</td> <td>Data 2</td> <td>Data 3</td> <td>Data 4</td></tr>
- ...
- </table>
Yeah, I know it's not proper semantics to intersperse <th> elements between <td> elements... that the <th>'s should be within a <thead> tag and that the <td>'s should be within a <tbody> tag. I know that I'd do better if the code could have each section in it's own little table, since they are each their own sets of tabular data. These are things I know, but may not be able to control (still working on whether I can get that part changed). In the meantime, for the sake of argument, let's pretend that I cannot alter the HTML.
The problem I am having is that I want to zebra stripe the code so that each group of rows that contains <td> elements, between the rows that contain <th> elements, is treated as its own group to zebra-stripe, so that the first row after each <th>-containing row is colored, alternating 'till the next <th> row, then starting again.
I am having a hard time coming up with proper selectors to do this. Here are some of my attempts:
- $('table.striped tr:even').addClass('altColor');
- /* of course, this doesn't discriminate against the <th> rows... I thought that specifying only tr.altColor td {} in the CSS would help, but it still counts those <th> rows while determining odd & even, throwing off the striping when there are single-row sections */
- $('table.striped tr:has("td"):even').addClass('altColor');
- /* just does the TDs, but doesn't start over after each <th> row, so not every section starts w/ a colored row. */
Any suggestions on just selecting those rows that are between <th> rows before I apply the :even selector, moving through each group where the odd/even count starts again?
Cheers!