Nth-child JQuery bit - can't understand the logic here


So, I’m up to the JQuery bit about using nth-child.

I’ve tried reading, re-reading, and re-re-reading the instructions for this bit, and no matter how many times I do, or even look at the code, I can’t understand why it works, or how.

.parent() is perfectly logical
.child() is perfectly logical
.nth-child() makes absolutely no sense to me.

Based on how .parent() and .child() work, it would seem, intuitively, that you would target the parent element, and then nth-child() would affect the indicated child beneath that. So, for this lesson, I would think you’d be targeting the class .well, and then targeting the child elements beneath that. But instead, it seems you’re targeting the ‘target’ class instead… But that wouldn’t make it children you’re targeting, but siblings.

I’ve seen a lot of other posts with people asking about it, and even with those explanations, it’s still not sinking in exactly how this is working or why.


I know it’s a little counter-intuitive, but the pseduoclass :nth-child() doesn’t look for the nth child of your target. It looks at all the things that meet your target parameters and selects the ones that are nth children If I do `$( “li:nth-child(3)” ).addClass(“red”);’ it is going to find every li that is a third child and apply the class red to it.

Hi, ksjazzguitar,

Thank you for your help!

After I wrote that post, I stepped away from the computer, took a walk and thought about it. As I was walking, what you explained started to occur to me, that the nth child thing is “parent agnostic”, so to speak; that it doesn’t matter what it’s the nth child of, just that it’s the nth child of something, and meets your criteria.

So, I’m glad to read your response and see that my suspicion was correct.

Cool! Thank you so much for helping me out with that!

This programming stuff requires a kind of thinking I’m not used to lol, so this is definitely an interesting journey :stuck_out_tongue: