Select first nested child in list but not subchilds
16,308
Solution 1
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:
ul.main > li > ul > li:first-child > a {
background:red;
}
Solution 2
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.
Author by
dude
Updated on June 26, 2022Comments
-
dude almost 2 years
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:How can this be solved?
-
Hashem Qolami over 9 years@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. -
dude over 9 yearsOk now I got it! The problem is without adding a class the selector will also be correct for the nested a-elements. Thank you!
-
GreyRoofPigeon over 9 years@HashemQolami, if the
ul
is a direct child of the body, you could also usebody > ul > li > ul > li:first-child > a
instead of an extra class. Or when the list has a parent, you could use:.parentClass > ul > .....
-
Hashem Qolami over 9 years@LinkinTED Absolutely. What I meant was having an identifier to determine the first
<ul>
. Either by giving it an ID, Class ro targeting it bybody > ul
, etc.