Link to home
Start Free TrialLog in
Avatar of coolispaul
coolispaulFlag for United States of America

asked on

jquery each loop

Hi,

Im trying to create a function that manipulates an unorderd list and creates nested unorders lists with 10 list items in each.

My functyion so far looks like:
$(".resources ul.book li").each(function(i, val) {
    
    if(i%10==0) {
      //$(this).append("<ul>");
      var newlist = $("<ul>").insertAfter($(this));
    }
    if(newlist) {
      newlist.append($(this));
    }
   i++;
});

Open in new window


newlist variable gets lost on each iteration - any ideas why?

Thanks
SOLUTION
Avatar of quizwedge
quizwedge
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of coolispaul

ASKER

yes that works

so variable scope is lost with the each() function because the function is effectively exited and entered again each time?

Thanks
Avatar of Chris Stanyon
You don't need the i++ - it automatically gets incremented with the each() call
Yep. FWIW, the value of "this" changes in the each loop as well. If you ever want to access "this" inside the each loop you have to do var saved_this = this outside of the loop.
'this' inside the each loop is the LI that you're on. You wouldn't have access to it outside the loop in the first place!

'this' outside the loop would refer to something else.
thanks chris - yeah i was getting confused

By the way , mu function is now
var newlist = '';
$(".resources ul.book li").each(function(i) {
    
    if(i%10==0) {
   
      newlist = $("<li><ul>").insertAfter($(this));
    }
    
      newlist.append($(this));
   
});

Open in new window


but this produces:

<ul class="book">
            <li><ul></ul>
           <li><a href="">one</a></li>
          <li><a href="">two</a></li>
</ul>

why is the ul in bold closed? i need the li to be inside the ul

Thanks
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
perfect thanks and thanks fo explaining why