views:

72

answers:

5

Hello, I have a set of selected elements in jQuery:

<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>
<div class="element"></div>

I would like to wrap these elements into groups of five like so:

<div class="wrapper">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
</div>
<div class="wrapper">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
</div>
<div class="wrapper">
    <div class="element"></div>
    <div class="element"></div>
</div>

Is there an efficient/easy way to do this? I imagine it would look something like this:

$('.element').wrapAll('<div class="wrapper"></div>');

But with a selector that selects the elements in groups of five.

Thanks!

A: 
var elements = [];
$('.element').each(function(index, element) {
    elements.push(element);
    if (index > 0 && index % 4 == 0) {
        $(elements).wrapAll('<div class="wrapper"></div>');
        elements.splice(0, elements.length);
    }
});
$(elements).wrapAll('<div class="wrapper"></div>'); 
Darin Dimitrov
A: 

If you're looking for a selector to do the job you can make use of 2, :gt() (greater-than) and :lt() (less-than):

$(".element:gt(9):lt(15)").wrapAll('<div class="wrapper"></div>');
$(".element:gt(4):lt(10)").wrapAll('<div class="wrapper"></div>');
$(".element:lt(5)").wrapAll('<div class="wrapper"></div>');

Just make sure you do it in reverse order :-)

Andy E
A: 

You can do it a bit mote compact like this:

var elems = $('.element');
for(var i = 0; i <= elems.length; i+=5) {
  elems.slice(i, i+5).wrapAll('<div class="wrapper"></div>');
}

This results in the exact result you have in the question :) You can make that 5 a variable and wrap the number of children you want, the remainder (in this case the last 2) will be wrapped in their own wrapper at the end.

Nick Craver
Nice! Thanks a lot!
scullytr
A: 
$('.element:nth-child(5n-4)').each(function(i){
    $(this).nextUntil('.element:nth-child(6n+'+i+')').andSelf()
        .wrapAll('<div class="wrapper"></div>');
});
PetersenDidIt
A: 
var elems = $('.element');
for(var i = 0; i <= elems.length-1; i+=5) {
  elems.slice(i, i+5).wrapAll('<div class="wrapper"></div>');
}

(changing elems.length to elems.length-1) Since arrays start at 0, elems.length would give you 12, but elems[12] is undefined;

I would recommend using the native for as it is much faster than .each()

path411