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 badges3 Answers
Reset to default 2Firstly, 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条)