javascript - jQuery: Get first element of type in top UL in a nested list - Stack Overflow

I have a nested list like this:<ul class="list"><li class="list_item_type_1&quo

I have a nested list like this:

<ul class="list">

    <li class="list_item_type_1">
        <ul class="list">
            <li class="list_item_type_2">Unnested item</li>
        </ul>
    </li>

    <li class="list_item_type_2">Unnested item</li>

</ul>

With jQuery I want to add a list item before all .list_item_type_2 in the first .list.

I write it like this:

$('.list:first').find('li.list_item_type_2:first').before('<li class="list_item_type_1">Nested list (...)</li>');

This won't work as intended because the script finds the first .list_item_type_2 in the second .list and appends the new code there instead.

How can I keep the search in the first ul and prevent it from entering underlying ul elements?

Cheers!

I have a nested list like this:

<ul class="list">

    <li class="list_item_type_1">
        <ul class="list">
            <li class="list_item_type_2">Unnested item</li>
        </ul>
    </li>

    <li class="list_item_type_2">Unnested item</li>

</ul>

With jQuery I want to add a list item before all .list_item_type_2 in the first .list.

I write it like this:

$('.list:first').find('li.list_item_type_2:first').before('<li class="list_item_type_1">Nested list (...)</li>');

This won't work as intended because the script finds the first .list_item_type_2 in the second .list and appends the new code there instead.

How can I keep the search in the first ul and prevent it from entering underlying ul elements?

Cheers!

Share Improve this question edited Dec 16, 2011 at 8:03 Web_Designer 74.8k93 gold badges210 silver badges267 bronze badges asked Sep 4, 2009 at 10:56 ChristofferChristoffer 26.9k18 gold badges54 silver badges77 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Firstly, I'd advise constructing HTML that way. Use jQuery to assemble the HTML. It takes care of escaping and all those other useful things:

$("<li></li>").addClass("list_item_type_1")
  .text("Nested list (...)")
  .prependTo("ul.list:first > li.list_item_type:first");

Also, always use a tag selector ("ul.list") over a naked class selector (".list") where possible. It's much faster on most browsers.

You were so close!

Instead of find(), which searches all descendants, use children(), which only searches children.

Test: http://jquery.nodnod/cases/723/run

Maybe try to bine the selector in one expression ?

$('.list:first > LI.list_item_type_2:first').before('<li class="list_item_type_1">Nested list (...)</li>');

The > selector does only match the direct children, as explained in the doc.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745141355a4613446.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信