TellJohn TellJohn - 2 months ago 9
HTML Question

nth-child not targeting the correct element?



.test:nth-child(1),
.test:nth-child(2),
.test:nth-child(3) {
color: #0F0
}

<div class="test">
<p>Test</p>
</div>
<div class="reuinIt">
<p>Test</p>
</div>
<div class="test">
<p>Test</p>
</div>
<div class="test">
<p>Test</p>
</div>





https://jsfiddle.net/dkfj2xzj/13/ <- UPDATED with my jQuery code if it helps

Why is it not skipping the
.ruinIt
class and not targeting the third
.test
?
I'm adding
<div>
s dynamically and when a
<div>
without the
.checkDrop
class is added I need to skip it.

Thanks

Answer

It's because the nth-child selector does not mean it's the nth of that specific class. It means that it's the nth sibling overall.

Have a look at Pseudo-classes

So the nth-child(2) refers to your .reuinIt class, however it does not also have the .test class and therefore it does not receive any styling.

Your last .test class is the nth-child(4) however that has no styling rules applied.