views:

373

answers:

3

Hey,

I have a nested list like this:

<ul class="list">
<li class="list_item_type_1">
  nested list
   <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 listitem 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!

+1  A: 

Maybe try to combine 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.

Wookai
Thank you. That worked!
Christoffer
+2  A: 

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.

cletus
Too slow...And I also like this, as it is, as you say, a better way of constructing the HTML using jQuery. +1
peirix
+1  A: 

You were so close!

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

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

cpharmston