chchrist
chchrist

Reputation: 19812

Get each first level li

I have this list

<ul>
    <li>
       <ul>
           <li></li>
           <li></li>
           <li></li>
       </ul>
    </li>
    <li></li>
    <li></li>
    <li></li>
</ul>

I need to get only the first level lis

Thanks in advance

Upvotes: 0

Views: 1157

Answers (4)

jfriend00
jfriend00

Reputation: 707326

Can't you use the direct child selector?

$("body > ul > li")

That should only return li tags that are direct children of the ul, whereas this:

$("ul li")

would return all descendant li tags and it would find li descendants under all levels of ul.

This whole selector would work a lot better if you put an ID on the UL that you want to get the first level li tags in. Then, your selector could be this:

$("#myID > li")

and it would be independent of where in your DOM it was located (whereas the first one has to be a direct child of the body tag to work).

Upvotes: 3

Dan Lugg
Dan Lugg

Reputation: 20592

Trying to keep it as general application as possible:

$('ul').filter(function(){
    return ($(this).closest('li').length == 0);
}).children('li');

Either answer from @Kokos or @jfriend00 are great. The only issue is if the <ul> is not a direct descendant of the <body>.

If this is a one-time scenario, perhaps post a bit more about it, and we can specify; otherwise without knowing more about the document structure, round-a-bout generalization (see above) attempts need be made.

Upvotes: 0

Pehmolelu
Pehmolelu

Reputation: 3564

On top of the Kokos and jfriend00 answers you can use:

$(selector).children();

To select just direct childs of selector. If you have that HTML selected in your selector already, just take its children.

Upvotes: 0

Kokos
Kokos

Reputation: 9121

Assuming the first ul is a direct child of body you can use this selector:

$('body > ul > li');

Upvotes: 3

Related Questions