A space changes the result of a :nth-child()?


When I add a space before/after the colon before "nth-child(4)" in the below code, like this "li :nth-child(4)" or "li: nth-child(4)", I fail to get the expected result. I really have no idea why this happens. Can anyone help me with this confusing problem? Thanks a lot.

// Write your jQuery code on line 3!
$(document).ready(function() {
    $target = $("ol li :nth-child(4)");
    //$target = $('ol li:nth-child(4)')


okay, really short explanation:


will select the a list element which is the 4th child of any parent.

on the other hand:

li :nth-child(4)

will select the 4th child inside any list element (<li></li>)

If you understand that, that would be awesome :slight_smile: Otherwise i will write a longer explanation


Thanks a lot for such a quick answer. I think I get what you mean: if a space is added after "li", the element following the space is a descendant and if no space is added, "li" and "nth-child(4)" are of a parallel relation. (Please correct me if I'm wrong).

And one more question: what about the space added after the colon: "li: nth-child(4)"? Why does this one work wrongly?


so far so good.

if this mean nth-child(4) will affect any list element which is 4th child, then yes

i believe that one is simply invalid.


Got it. Thanks a lot for your help!