Select first nested child in list but not subchilds
Asked Answered
B

2

8

I have a unordered list like:

<ul>
    <li>Element one
        <ul>
            <li><a>Element two</a>
                <ul>
                    <li><a>Element three</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Now if I try to select the <a>-element of "Element two". I would do it like the following:

ul ul li:first-child > a

This will select also the following nested <a> element. See this fiddle:

http://jsfiddle.net/38ksdpw3/

How can this be solved?

Bowdlerize answered 17/9, 2014 at 9:46 Comment(1)
w3schools.com/Css/css_combinators.aspBolognese
G
18

You probably need to add an identifier to the first <ul> element and then walk through the children tree by parent > child children selector as follows:

Example Here

ul.main > li > ul > li:first-child > a {
    background:red;
}
Groos answered 17/9, 2014 at 9:50 Comment(4)
@julmot The .main identifier in this case acts as a start point which makes the selector start from that level in the DOM to match the the desired element at the end.Groos
Ok now I got it! The problem is without adding a class the selector will also be correct for the nested a-elements. Thank you!Bowdlerize
@HashemQolami, if the ul is a direct child of the body, you could also use body > ul > li > ul > li:first-child > a instead of an extra class. Or when the list has a parent, you could use: .parentClass > ul > .....Concha
@LinkinTED Absolutely. What I meant was having an identifier to determine the first <ul>. Either by giving it an ID, Class ro targeting it by body > ul, etc.Groos
J
1

Actually you can not diffirintiate it in such structure. For both links you have ul ul li:first-child > a applied without the specific parent. So you should consider to use classes (at least for parenting) instead of tags.

Jaymejaymee answered 17/9, 2014 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.