3

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()

1
  • I want to have something that starts with $(this) and ends with .each(). Is there a particular reason for this constraint (seems kind of arbitrary)? Commented Jun 2, 2010 at 16:06

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1, see jsfiddle.net/buMsx for the top one working. I'm not quick enough on the draw :)
it wouldn't work for sure as each() can't work after find(). find by itself would return one element only
@bhefny - sorry, but that's not correct. find will return as many elements as are matched by the passed selector.
4

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.

Comments

3

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').

2 Comments

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: Yes, you can. However, there might be other <li>'s.
0

This might work:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.