views:

151

answers:

5

Hello,

I have the following code

  <div>
 <a href="#" class="clickMe">test</a>
 <ul>
     <li class="action_li">1</li>
     <li class="action_li">2</li>
 </ul></div> <div>
 <a href="#" class="clickMe">test</a>
 <ul>
     <li class="action_li">3</li>
     <li class="action_li">4</li>
 </ul>

and I want to loop on all the <li> that are enclosed with the same <div> as the clicked <a>

$("a.clickMe").live("click", function(eve){
   eve.preventDefault();
   $('.action_li').each(function(index) {
      console.debug(this);
   }); 
});

but of course this will get me all the 4 <li> not the two enclosed so I want to have something that starts with $(this) and ends with .each()

+3  A: 

You need to get the <ul> element that is a sibling of the <a>, then get its children.

For example:

$(this).siblings('ul').children('li.action_li').each(function(index) {
    //...
});

You could also call $(this).next() or $(this).nextAll('ul').

SLaks
I think you can just use '.action_li' instead of 'li.action_li' or just plain 'li'... it's faster for jquery's selector engine
ricecake5
@ricecake5: Yes, you can. However, there might be other `<li>`'s.
SLaks
+5  A: 

There are many ways, examples:

   $(this).parent().find("li.action_li").each(function(index) {
      console.debug(this);
   }); 

or:

   $(this).next("ul").children("li.action_li").each(function(index) {
      console.debug(this);
   });

etc.

karim79
+1, see http://jsfiddle.net/buMsx/ for the top one working. I'm not quick enough on the draw :)
David Waters
it wouldn't work for sure as each() can't work after find().find by itself would return one element only
bhefny
@bhefny - sorry, but that's not correct. find will return as many elements as are matched by the passed selector.
karim79
A: 
$("a.clickMe").live("click", function(eve){
   eve.preventDefault();
   $(this).siblings('ul').children('li').each(function(index) {
      console.debug(this);
   }); 
});
jAndy
+4  A: 

This should work:

$("a.clickMe").live("click", function(eve){
   eve.preventDefault();
   $('.action_li', $(this).parent()).each(function(index) {
      console.debug(this);
   }); 
});

Second parameter next to the selector will limit the search to only part of the DOM tree, in this part to the one div which is parent for a element.

RaYell
I can't thank you enough.it worked like a charm.
bhefny
A: 

This might work:

$(this).parents('div').find('li').each(...
Jeremy