Issue:
selector:not(.hidden):nth-child(even)
is selecting elements that are both not hidden and even. However, the requirement is to only select a subset of even elements from those without the .hidden class. In simple terms, the
:nth-child(even)
part in
selector:not(.hidden):nth-child(even)
is disregarding the
:not(.hidden)
part and acting independently, not selecting even elements from visible ones. This default behavior of
nth-child
cannot exclude hidden rows as they still exist in the DOM.
Resolution 1 (functional)
Instead of hiding table rows, completely eliminate them. Preserve a list of references to the DOM elements representing table rows in their initial state. During filtering actions, iterate through this array and based on the filter conditions, either utilize the append
method for the table or the remove
method for the row
Replace
if (condition) {
row.classList.add('visible')
} else {
row.classList.add('hidden')
}
with
// pseudocode snippet
const rows = Array.from(tbody.querySelectorAll<HTMLTableRowElement>('tr'));
onClickOneOf(filterAction, (event) => {
// ...custom logic
for (const row of rows) {
if (condition) {
tbody.appendChild(row);
} else {
row.remove();
}
}
});
now nth-child
will function accurately
Resolution 2 (partially supported but effective)
Resource: https://developer.chrome.com/articles/css-nth-child-of-s/#zebra-striping-revisited
A common scenario involving the use of :nth-child()
- when implementing zebra striping in tables. The conventional approach is as follows:
tr:nth-child(even) {
background-color: lightgrey;
}
This approach works well with static tables, but encounters challenges when dynamically altering the table content.
To address this issue, we can employ :nth-child(An+B [of S]?)
by excluding the hidden rows from the An+B logic:
tr:nth-child(even of :not(.hidden-class or other...)) {
background-color: lightgrey;
}