Dmitriy Zhernoviy
Dmitriy Zhernoviy

Reputation: 111

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 firstVariant

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

secondVariant

Upvotes: 0

Views: 1670

Answers (3)

Toan Lu
Toan Lu

Reputation: 1239

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.

Though the second selector of yours is correct as <li> are siblings.

Upvotes: 0

Barmar
Barmar

Reputation: 781004

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.

Upvotes: 3

Dylan
Dylan

Reputation: 343

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.

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.

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.

Upvotes: 0

Related Questions