Justin Clarke
Justin Clarke

Reputation: 139

Wrap Group of Classes With HTML

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>

Upvotes: 0

Views: 48

Answers (2)

Alex W
Alex W

Reputation: 38173

You can also loop through and wrap them:

for(var i = 1; i <= 2; i++)
{
    $('.foo'+i).wrapAll('<ul/>');
}

Or if you don't know how many there will be:

var i = 1;
while($('.foo'+i).length > 0)
{
    $('.foo'+i).wrapAll('<ul/>');
    i++;
}

Upvotes: 0

Barbara Laird
Barbara Laird

Reputation: 12717

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/>');
});

http://jsfiddle.net/bhlaird/C5Dzn/

Upvotes: 2

Related Questions