Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping a div around every three divs

Tags:

jquery

Say I have 6 child divs and they don't have unique identifiers:

<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>

With jQuery, I want to wrap every set of 3 with <div class="parent"></div>. So it would render as:

<div class="parent">
     <div class="child"></div>
     <div class="child"></div>
     <div class="child"></div>
</div>
<div class="parent">
     <div class="child"></div>
     <div class="child"></div>
     <div class="child"></div>
</div>

What's the easiest way to do this?

like image 390
EdwardM Avatar asked Jul 14 '11 16:07

EdwardM


3 Answers

Wow, nice challenging question =)

while(($children = $(':not(.parent)>.child:lt(3)')).length) {
    $children
        .parent()
        .append(
            $('<div class="parent"></div>')
                .append($children.remove())
    );
}

Edit: Didn't know about the wrapAll method, so:

while(($children = $(':not(.parent)>.child:lt(3)')).length) {
    $children.wrapAll($('<div class="parent"></div>'));
}
like image 167
Dereleased Avatar answered Oct 24 '22 19:10

Dereleased


This should do it:

var $children = $('.child');
for(var i = 0, l = $children.length; i < l; i += 3) {
    $children.slice(i, i+3).wrapAll('<div class="parent"></div>');
}

DEMO

like image 31
Felix Kling Avatar answered Oct 24 '22 18:10

Felix Kling


There's a small plugin I've written which I use in scenarios like this. It takes a collection, and splits it in to chunks of x (where x is the size of each chunk):

$.fn.chunk = function( cLen ) {
    var chunks = [];
    while ( this.length ) {
        chunks.push( this.splice(0, cLen) );
    }
    return $(chunks);
};

It can then be used like this:

$('.child').chunk(3).each(function() {
  $(this).wrapAll('<div class="parent">');
});

Here's a fiddle

Or, as a plugin for this purpose:

$.fn.wrapEvery = function( cLen, wrapperEl ) {
    while ( this.length ) {
        $( this.splice(0, cLen) ).wrapAll( wrapperEl );
    }
};

Which could be used like this:

$('.child').wrapEvery(3, '<div class="parent">');

Here's another fiddle

like image 4
billyonecan Avatar answered Oct 24 '22 19:10

billyonecan