开发者

Select all li's but not children

开发者 https://www.devze.com 2022-12-22 22:28 出处:网络
I have this code: $li = $(\"li\", this) Which is selecting all of the li\'s in my code. This works fine however I want $li to exclude the li\'s that are within a submenu.

I have this code:

$li = $("li", this)

Which is selecting all of the li's in my code. This works fine however I want $li to exclude the li's that are within a submenu.

    <ul id="navigation">
        <li><a href="#">blah 1</a></li>
        <ul id="subnav">
            <li><a href="#">sub 1</a></li>
            <li><a href="#">sub 2</a></li>
            <li><a href="#">sub 3</a></li>
        </ul>
        </li>
        开发者_开发知识库<li><a href="#">blah 2</a></li>
        <li><a href="#">blah 3</a></li>
        <li><a href="#">blah 4</a></li>
        <li><a href="#">blah 5</a></li>
    </ul>

So $li would only reference the blah's not the sub's.

I thought it was something like:

$li = $("li", this).parents()

But this doesn't do what I want.


Just use the child selector >:

$("#navigation > li")


You want to use the immediate child selector, >:

$li = $('#navigation > li');


var li = $("#navigation > li");

The > selects only direct children


Future Googlers may find this answer useful if they are here (like me) looking for Select all li's without any children

$("#mylist li:not(:has(ul))")

or

$("#mylist li:not(:has(li))")
0

精彩评论

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