I have an unordered list that has about 25 list items that have different classes after each 5 list items. Example below.
<ul>
<li class="foo1">Hello</li>
<li class="foo1">Hello</li>
<li class="foo1">Hello</li>
<li class="foo1">Hello</li>
<li class="foo1">Hello</li>
<li class="foo2">Hello</li>
<li class="foo2">Hello</li>
<li class="foo2">Hello</li>
<li class="foo2">Hello</li>
<li class="foo2">Hello</li>
</ul>
I need to wrap each 5 list items within that class in an ul. These list items are outputted by a CMS, so I can't code it myself. I know I can use jquery .wrap() on the class, but that would wrap each list item with that class in an ul. So how can I wrap the 5 list items that have the class with an ul?
The output should be this:
<ul>
<ul>
<li class="foo1">Hello</li>
<li class="foo1">Hello</li>
<li class="foo1">Hello</li>
<li class="foo1">Hello</li>
<li class="foo1">Hello</li>
</ul>
<ul>
<li class="foo2">Hello</li>
<li class="foo2">Hello</li>
<li class="foo2">Hello</li>
<li class="foo2">Hello</li>
<li class="foo2">Hello</li>
</ul>
</ul>
You're looking for $('.foo1').wrapAll('<ul/>');
Added a jsfiddle that finds the classes within the ul and wraps them (in case you don't know the inner class names going in).
function classList(elem){
var classes = [];
$.each( elem, function(index,item) {
elemClasses = $(item).attr('class').split(/\s+/);
$.each(elemClasses, function(index,item) {
if(classes.indexOf(item) === -1) classes.push(item);
});
});
return classes;
}
$.each(classList($('ul li')), function(index, item) {
$('.' + item).wrapAll('<ul/>');
});