3

Let's take this HTML for example:

<ul class="wrap">
 <li class="out"></li>
 <li class="out"></li>
 <li class="out">
     <ul class="wrap">
        <li class="out"></li>
        <li class="out"></li>
     </ul>
 </li>
</ul>

Using jQuery, what's the best way of targeting the list item that had a class of "wrap" but is not a child of the nested ul? Alternatively, how can I taget the li with a class of "wrap" that is nested in a ul which is nested in an li?

4 Answers 4

4

For the un-nested li, you have two options:

$('ul.wrap:has(ul) > li') // For uls that specifically have a nested ul inside
$('ul.wrap > li:not(ul ul > li)') // For any top-level ul

For the nested li:

$('ul.wrap ul.wrap > li')
Sign up to request clarification or add additional context in comments.

Comments

1

ul which is nested with li:

$("li > ul.wrap > li")

ul which is not nested with li:

$("ul.wrap li:not(li > ul >li)")

Comments

0

something like this, I believe:

$("ul.wrap li ul.wrap")

Comments

0

You have an "outer" ul and an "inner" ul. Selecting the inner ul is very easy, you just use a descendent-selector ul.wrap ul.wrap. In outer one is a little bit tricky, because you'll need to use a condition with a not selector: ul.wrap:not(ul.wrap ul.wrap). You're basically saying: give me all the ul.wrap that do do not have a parent that have a wrap. If you want to select the "li's" use the direct selector i.e. > li behind each selector.

I've added it to an example for you to show it works:

Html:

<ul class="wrap" tag="outer">
 <li class="out"></li>
 <li class="out"></li>
 <li class="out">
     <ul class="wrap" tag="inner">
        <li class="out"></li>
        <li class="out"></li>
     </ul>
 </li>
</ul>

JQuery:

alert($('ul.wrap:not(ul.wrap ul.wrap)').attr('tag'));
alert($('ul.wrap ul.wrap').attr('tag'));

alert($('ul.wrap:not(ul.wrap ul.wrap) > li').length);
alert($('ul.wrap ul.wrap > li').length);

Ps. I wouldn't use 'li' selector to find the outer or inner ul. You might encounter empty ul's if you fill them programatically (which will break a selector with that's dependent on li) and why should you use something you don't need?

1 Comment

It migth be useful to read a little bit about selectors on this page: api.jquery.com/category/selectors. Have fun!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.