Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS nth-child property does not work correctly when dynamically adding items

I have some divs defined in my page

<div class="alternating">random text</div>
<div class="alternating">random text</div>
<div class="alternating">random text</div>
<div class="alternating">random text</div>
<div class="alternating">random text</div>

I have added a css property

.alternating:nth-child(even){
    background: #FF0000;
}

On the loading the page everything seems fine and the even rows are colored. But when I add a new div to the parents of this divs (using Knockout and jquery) the newly adding row does not show the right color. That means if my last line was odd (no color) the newly added div also appears with no color. Or if the last div was even (with color) the newly added div also appears with color.

But after that it works out normal again. My problem is only on the addition of the 1st div.

Any ideas?

like image 547
Nisho Avatar asked Sep 13 '26 01:09

Nisho


1 Answers

Here's a little FIDDLE in which I start with divs in the DOM, then add them by a click.

Relevant: JS

$('.button').click(function() {
    $('.holder').append("<div class='inside'>dynamic div</div>");
});

Relevant CSS

.holder {
    width: 300px;
    height: 400px;
    border: 1px solid black;
}
.inside {
    height: 30px;
    border: 1px solid black;
}
.inside:nth-child(even) {
    background-color: blue;
}
like image 190
TimSPQR Avatar answered Sep 16 '26 13:09

TimSPQR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!