views:

35

answers:

2

Hi, I'm using a bit of code suggested by a member on stackoverflow and adapted by me to wrap every 3 li items as part of a mega menu. The code is:

var lis = $("ul > li");
for(var i = 0; i < ls.length; i+=3) {
  lis.slice(i, i+3).wrapAll("<div class='new'></div>");
}

Unfortunately this will grab child li's from the next parent menu to fill up the 'quota' of 3 li's in a div. This is of course massively messing up my menus. For an example please visit here

Does anyone have any suggestion how I could fix this up

Many thanks for any assistance

A: 

have you tried applying it withe the use of the class as ht selector like this?

var lis = $("ul.list-content > li");
for(var i = 0; i < lis.length; i+=3) {
  lis.slice(i, i+3).wrapAll("<div class='new'></div>");
}

But if you did not know, I'm warning you that you are breaking the dom.. you are putting div on ul which is not good.. ;)

Reigel
+2  A: 

Your problem is your selector. Since sizzle works right to left, it will just query all LI elements which have an UL element as direct parent (which usually, is always the case).

So, seperate your ULs.

$('ul').each(function(){
   var $lis = $(this).children('li');
   for(var i = 0, len = $lis.length; i < len; i+=3){          
     $lis.slice(i, i+3).wrapAll("<div class='new'></div>");
  }
});
jAndy
Thanks for the info Andy - apologies but I'm very new to jQuery. I think I understand the logic behind what you're saying but unfortuantley I'm unable to get the code snippet you sent working on the demo I included above... Also would this not end up wrapping every 3 li's on a page? Would it be better to specify ul.list-content as the the ul?thanks for any advice
csbourne
jAndy
hmmn - sorry still no joy with the code above. Does it work for you?
csbourne
@csbourne: well I'm fooling around at http://www.jsfiddle.net/cbnFX/It at least does what I'm expecting :) But I don't have that plugin available there.
jAndy
@jAndy - sorry I had a small error in my code. You're a life saver - thanks for your help!
csbourne