How can I select the link elements of only the parent <ul>
from a list like this?
<ul> <li><a href="#">Link</a></li> <li><a href="#">Link</a> <ul> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> </li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li>
So in css ul li a
, but not ul li ul li a
Thanks
The :first selector selects the first element.
Element Selectors The most basic of the selectors is an element selector. For example, paragraphs in an HTML document are represented by the p element and wrapped in <p></p> tags. To select all paragraphs in a document we would use the following selector. To select all level 1 headings we would use the h1 selector.
The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
$("ul > li a")
But you would need to set a class on the root ul if you specifically want to target the outermost ul:
<ul class="rootlist"> ...
Then it's:
$("ul.rootlist > li a")....
Another way of making sure you only have the root li elements:
$("ul > li a").not("ul li ul a")
It looks kludgy, but it should do the trick
Once you have the initial ul, you can use the children() method, which will only consider the immediate children of the element. As @activa points out, one way to easily select the root element is to give it a class or an id. The following assumes you have a root ul with id root
.
$('ul#root').children('li');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With