I am playing around with adding content from an array to a table on my page that in code, only has a header row, and a CSS selector which sets the container div to “display:none;”. Immediately after the table declaraton, I created a small script on my HTML page which is dynamically adding rows to a table like so:
<div id="div-load">
<h1>Popular Disney Characters by Merchandise Sales</h1>
<table id="table-fill" class="table-style">
<tr>
<th>Character</th>
<th>Rank</th>
</tr>
</table>
<script>
let characters = ["Mickey Mouse", "Minnie Mouse", "Goofy", "Donald Duck", "Pluto"];
let charTable = document.getElementById("div-load");
for (let i = 0; i < characters.length; i++) {
let charRank = i + 1;
let tr = "<tr><td>" + characters[i] + "</td><td style='text-align:center;'>" + charRank + "</td></tr>";
document.getElementById("table-fill").innerHTML += tr;
}
if (characters.length > 0) {
charTable.style["display"] = "block";
}
</script>
</div>
I also have the following CSS selector to color the rows of the table:
tr:nth-child(even) {
background-color: #76d0c0;
}
I have other selectors which apply to this table and those are being applied correctly to both this dynamically created one, and another statically created table on the page, so I will ignore those for the context of this issue…
Anyway, when I load the page with an empty array, my if statement returns false as expected, and the page is not on the screen. When I add values to the array, I’m finding that the background-color attribute is not being applied to the rows, I’m adding, so I get the following result:
But if I change my CSS selector to just “tr”, then I get this result:
As you can see in the images, the tr selector is being properly applied to the static table, so I’m discounting a bug in the CSS selector for now. Is there a bug in the way nth-child is processed when it comes to dynamic content, or is there a preferred way to implement nth-child styling dynamically? I suppose I could add logic to my script to add the style inline, but considering that dynamic styling works otherwise, it feels inefficient.
As mentioned above, simply commenting out the nth-child specification applied he expected styling dynamically, so I’m just a little confused as to why nth-child fails. I also verified that this behaves the same in Chrome and Edge browsers.