Reputation: 173
I have multiple divs like this:
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="large"></div>
<div class="large"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
I want to select every 4 .small divs to wrap in another div so it's like this:
<div class="box">
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
<div class="small"></div>
</div>
As you can see from the first example, there can be more than 4 adjacent ones, but I still want to group every 4 .small divs.
Any idea would be much appreciated. Thanks!
Upvotes: 1
Views: 232
Reputation: 490597
Here is how I've done it in the past.
var smallDivs = $('div.small'),
chunkLength = 4;
for (var i = 0, length = smallDivs.length; i < length; i += chunkLength) {
smallDivs.slice(i, i + chunkLength).wrapAll('<div class="box" />');
}
I chunk the selected elements into chunks of a desired length and then call wrapAll()
on the sub-selection.
Just for the hell of it, here is how you'd do it without jQuery...
var smallDivs = document.querySelectorAll('div.small'),
chunkLength = 4,
box;
for (var i = 0, length = smallDivs.length; i < length; i++) {
if (!(i % chunkLength)) {
box = document.createElement('div');
box.className = 'box';
smallDivs[i].parentNode.appendChild(box);
}
box.appendChild(smallDivs[i]);
}
Of course, for old browsers that don't support document.querySelectorAll()
or document.getElementsByClassName()
, replace the element selecting code with...
var divs = document.getElementsByTagName('div'),
smallDivs = [];
for (var i = 0, length = divs.length; i < length; i++) {
if ((' ' + divs[i].className + ' ').indexOf(' small ') >= 0) {
smallDivs.push(divs[i]);
}
}
Upvotes: 5
Reputation: 3290
You use slice
or gt()
and lt()
See example below
$(".small").slice(4,10).wrapAll('<div class"smallWrapper"></div>');
Or
$(".small:gt(5):lt(10)").wrapAll('<div class"smallWrapper">
Upvotes: 0