How to fix background-color(static) of table rows in HTML if the data changes dynamically?

Viewed 125

I have an order table, where orders are going in and out, and I have to fix background-color of entire rows( I mean in every three lines the background color is changing in a loop). For example:

#orders tr:nth-child(3n+3) {
    background: #e7eff6;
}

#orders tr:nth-child(3n+4) {
    background: #d0e1f9;
}
    
#orders tr:nth-child(3n+2) {
    background: #adcbe3;
}

But there's a problem, because if an order is going in or an order is being canceled and going out, then the rows background-color is going to change, but I have to fix it and remain the color what firstly got.

So, I need to separate rows, not necessary by background-colors, but it must to be fixed if the data is changing dynamically.

Does anybody have an idea?

1 Answers

You can use modulus % in JS for setting background color for rows once on load. For example if your table have id=tableId, you can run something like that

let tableEl = document.getElementById("tableId");
let index = 0;
let colors = ["#e7eff6","#d0e1f9","#adcbe3"]
for (let trEl of tableEl.rows) {
    trEl.style.backgroundColor = colors[index % colors.length];
    index++;
}
Related