Nth-child direct child on nested lists

I can not find a solution to this problem presented on this fiddle . I have a list, and inside this list I have another list with items. I want to select the second direct child of the first list, but what happens is that the second element in the second list is also selected. How can I choose only the second 2nd child of the first list?

<ul id="list-1">
    <li>Item 1
        <ul id="list-2">
            <li>Item 1 Child 1</li>
            <li>Item 1 Child 2 (I don't want this one to be red)</li>
        </ul> 
    </li>
    <li>Item 2 (I only want this one to be red)</li>
    <li>Item 3</li>
</ul>

I am currently trying to access it: $("#list-1 li:nth-child(2)").css("color", "red");

+4
source share
1 answer

You need to use a direct descendant selector >:

$("#list-1 > li:nth-child(2)").css("color", "red");

Updated script

+3
source

Source: https://habr.com/ru/post/1585098/


All Articles