views:

2553

answers:

4

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

+6  A: 
$("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

Philippe Leybaert
Hmm I discovered my problem was with using jquery 1.2. I've replaced it with 1.3 and these kind of selectors are working fine now. Thanks very much for your reply and everyone who replied.
aston
A: 

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');
tvanfosson
+1  A: 

You can also use $("ul li:first-child") to only get the direct children of the UL.

I agree though, you need an ID or something else to identify the main UL otherwise it will just select them all. If you had a div with an ID around the UL the easiest thing to do would be$("#someDiv > ul > li")

Chris Barr
A: 

.add_to_cart >>> .form-item:eq(1)

the second .form-item at tree level child from the .add_to_cart

isidoro