I have groups of unordered lists and I am trying to divide each list group into sub-groups of 3 dynamically. So far I have this:
var uls = $("ul > li");
for(var i = 0; i < uls.length; i+=3) {
uls.slice(i, i+3).wrapAll("<ul class='new'></ul>");
}
… for some sample HTML below
<h2>Group 1</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<h2>Group 2</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
</ul>
The issue I am having is that my code just lumps all the <ul>s together without regard to groups, i.e. ‘group 1’ ‘group 2’ I tried using .each(function() { on $("ul > li") but I just get errors. I also tried moving down the each function after .length but that did not work either.
So the final HTML would look like this:
<h2>Group 1</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<ul>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<h2>Group 2</h2>
<ul>
etc...
My fiddle is here but as you can see it’s not quite working yet.
How’s this? http://jsfiddle.net/4Bms6/
The reason you were getting incorrect grouping is because you were starting off by collecting every single li (“ul > li” equates to all li that are children of any ul). What you should have been doing is selecting all li that are children of each ul, perform the grouping, then move on to the next ul.