CSS Select a 2nd descendant
CSS Select a 2nd descendant
I'm using Chrome Debugging tool to find elements on a page. I am having trouble understanding the logic.
The piece of HTML looks like this
Here is my first solution 
It is a menu where I'm trying to select a second link for "Logout". But it doesn't recognize "a" as descendant of a "div".
But when I select it, a child of an element which is descendant of a "div" it finds it
Can someone explain why I cannot find it when I do it as on the first picture

3 Answers
3
Based on MDN Web Docs
https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
The :nth-child() CSS pseudo-class matches elements based on their position in a group of siblings.
Clearly here the <a> is not being siblings of each other, so your selector is not correct on the first image.
<a>
Though the second selector of yours is correct as <li> are siblings.
<li>
a:nth-child(2) matches an <a> element that's the second child of its immediate parent. But each <li> only has one child, there's never a second child. It's the <ul> elements that have multiple <li> children, so you need to put the :nth-child modifier on li, and then select the <a> within that.
a:nth-child(2)
<a>
<li>
<ul>
<li>
:nth-child
li
<a>
The :nth-child() pseudo-class only selects elements that are the nth-child of their direct parent, it doesn't work for an arbitrarily high ancestor.
:nth-child()
The reason it does not work in your first solution is because each a is the first child of its parent (li). Since each a is the first child, :nth-child(2) won't select any a.
a
li
a
:nth-child(2)
a
The reason it works in your second solution is because you are selecting the second li. The parent of li is ul, and ul has two li elements in it, so li:nth-child(2) is able to find the second li.
li
li
ul
ul
li
li:nth-child(2)
li
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
thank you for detail explanation
– Demitri Zhernovyi
Jul 6 at 15:21