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?
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
(wherex
is the size of each chunk):It can then be used like this:
Here's a fiddle
Or, as a plugin for this purpose:
Which could be used like this:
Here's another fiddle
This should do it:
DEMO
Wow, nice challenging question =)
Edit: Didn't know about the
wrapAll
method, so: