开发者

How to target a specific parent div using jQuery

开发者 https://www.devze.com 2023-02-05 01:27 出处:网络
Let\'s take this HTML for example: <ul class=\"wrap\"> <li class=\"out\"></li> <li class=\"out\"></li>

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 n开发者_JAVA百科ot 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?


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')


ul which is nested with li:

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

ul which is not nested with li:

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


something like this, I believe:

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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号