I'm working on a table that has clickable rows. When you click a row, a new row will be appended right after the one you clicked.
// before click
<tr role=row>...</tr>
<tr role=row>...</tr>
//after clicking the 1st tr
<tr role=row>...</tr>
<tr>...</tr>
<tr role=row>...</tr>
What I need is that the rows with role="row" get alternating colors and the trs without the role get ignored.
This is what I have so far:
$('tr[role=row]').click(function () {
if ($(this).attr('data-toggle') != 0) {
$(this).after('<tr colspan="4"><td>-</td></tr>')
.attr('data-toggle', 0);
}
});
.myclass > tbody > tr[role=row]:nth-child(odd) td {
background-color: #fad;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="myclass">
<thead>
<tr role="row">
<th>head 1</th>
<th>head 2</th>
<th>head 3</th>
<th>head 4</th>
</tr>
</thead>
<tbody>
<tr role="row">
<td>should</td>
<td>be</td>
<td>colored</td>
<td>!</td>
</tr>
<tr role="row">
<td>no</td>
<td>color</td>
<td>-</td>
<td>-</td>
</tr>
<tr role="row">
<td>should</td>
<td>be</td>
<td>colored</td>
<td>!</td>
</tr>
<tr role="row">
<td>no</td>
<td>color</td>
<td>-</td>
<td>-</td>
</tr>
</tbody>
</table>
The problem is whenever you add a new row (without role) it still counts for the css selector and the rows with role="row" get wrongly changed.
In short: I want a zebra style only applied on trs with role="row" that keep their color even when a row is inserted
If it can't be done in CSS, jquery is also fine.
Any help & feedback would be appreciated!
EDIT:
- Temani Afif's answer is nice, but I need to keep this table as it is.
- The third solution of Temani Afif's works best for me.