Is it possible to use nth-child
selectors to wrap 3 divs using .wrapAll
? I can't seem to work out the correct equation.
so...
<div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
becomes...
<div>
<div class="new">
<div></div>
<div></div>
<div></div>
</div>
<div class="new">
<div></div>
<div></div>
<div></div>
</div>
</div>
You can do it with
.slice()
, like this:You can try out a demo here, all we're doing here is getting the elements you want to wrap and looping through them, doing a
.wrapAll()
in batches of 3 then moving to the next 3, etc. It will wrap 3 at a time and however many are left at the end, e.g. 3, 3, 3, 2 if that's the case.The Plugin
How to use it.
Call
EveryWhat()
on the element and put in a number for every element you would like to collect.wrapinner's quotes should have a properly formatted
<div class="new" />
with a class and closing tag. Stackoverflow prevents me from showing what that looks like but here is a link of a self closing div.What it should look like
That will wrap every other number that you specified. I'm using jquery 1.8.2. so remember use selector call
EveryWhat(3)
and a number for every time. Of course putting it at the bottom of the page or wrapping it in aYou could use every nth and then
.wrapInner('<div class="new" />')
for the same results.I've written a generic chunk function that makes this quite easy to do:
Here is a more usable version of Nick's above:
You would use this like:
window should be replaced with your Handlers namespace, of course.
Updated: A slightly better version that leverages jQuery
Use like:
The second parameter for the wrapper name is optional.
I took Kyle's plugin idea and extended it to wrap automatically and take two arguments. It didn't work for me to begin with, but I got it running with a few edits and additions to the code.
To invoke the function just use the parent element of what you want to wrap and then set your arguments as follows.
The first argument is how many elements you want to wrap together and the second argument is the element type you would like to wrap.
You can change the class of the wrapping element in the main function under the variable
wrapClass
.I have prepared this answer for another question that was duplicate of this one. So maybe my variant will be usefull for some one:
I think the solution to wrap all three elements is:
I have wrote the same code at jsbin with some improvements http://jsbin.com/necozu/17/ or http://jsbin.com/necozu/16/