Fired from Amazon.com
Fired from Amazon.com

Reputation: 265

How do I do a nested for-each loop with JQuery to get specific li elements?

What I'm trying to do is essentially go through uls which are organized like

<ul class="some-ul">
    <li class="some-li"></li>
    <li></li>    
    <li></li>
    <li class="some-li"></li>
</ul> 
<ul class="some-ul">
    <li class="some-li"></li>
    <li></li>    
    <li></li>
    <li></li>
</ul> 
<ul class="some-ul">
    <li class="some-li"></li>
    <li class="some-li"></li>    
    <li class="some-li"></li>
    <li class="some-li"></li>
</ul> 

and do something with the lis of class some-li and something else with the lis that don't have that class. So, it would be equivalent to

$('ul.some-class li.some-class').each(function() {
   // do something
});

$('ul.some-class li:not(.some-class)').each(function() {
   // do something else
});

except I want to do it like

$('ul.some-class').each(function() {
     // loop through the list elements of this list 
});

but I don't know how to construct that inner loop. Is this possible, and if so, what tool should I using?

Upvotes: 3

Views: 1989

Answers (4)

Michael Schmitt
Michael Schmitt

Reputation: 139

The callback of the each call gets the index and the element as arguments.

This way you can

$('ul.some-class').each(function(i, elt) { 
     $(elt, 'li.some-class').each ...
 });

https://api.jquery.com/jquery.each/

Upvotes: 0

Barmar
Barmar

Reputation: 780724

Within .each, this will be the current element of the iteration. You can then use $(this).find() to find elements within it:

$('ul.some-ul').each(function(i, ul) {
    $(ul).find("li").each(function(j, li) {
        // Now you can use $(ul) and $(li) to refer to the list and item
        if ($(li).hasClass('some-li')) {
            ...
        }
    });
});

Upvotes: 3

Downgoat
Downgoat

Reputation: 14361

You can use hasClass and a CSS selector to get all immediate children (The <li>s).

$('ul.some-class > li').each(function() {
     if ($(this).hasClass('some-class')) {
         //Do something
     } else {
         //Do something else
     }
});

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Loop through all the <li> and use hasClass() to see if they fit the class you want or not and react accordingly

$('.some-ul').children().each(function(){
   // "this" is current li
   if ( $(this).hasClass('some-li') ){
       $(this).doSomeClassThing();
   } else {
        $(this).doNoClassThing();
   }    
});

One pass through and you are done

Upvotes: 0

Related Questions