views:

109

answers:

1

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>

Many thanks for any help :)

+4  A: 

You can do it with .slice(), like this:

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

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.

Nick Craver
I'd make this a function and make the number of wrapped divs an argument. Something like applyDivGrouping( divs, divsPerGroup );
Stefan Kendall
+1 Nice solution, Nick.
Gert G
csbourne
@csbourne - Nope `:nth-child()` doesn't lend it self well to this, as for calling this, just wrap it in a `$(function() { });` if you want to run it on `document.ready`, otherwise call it when you want to run it :)
Nick Craver
Thanks Nick for the fantastic help and guidance - works perfectly.
csbourne
@csbourne - Welcome :) Be sure to accept answers on this and future questions via the check beside the one that resolved your issues, as you go it'll help make your questions more appealing to answer, meaning more people helping you solve your problems :)
Nick Craver
@Nick - I've been testing this solution on the more complex 'live' scenario (I just used divs for the demo... Basically - in the real scenario- the div's are <li>s as part of a mega menu.There is a strange quirk whereby the code you suggested 'borrows' a <li> from the next parent <li> to make the count up to 4 in a row. Sorry I'm sure that's really poorly explained - maybe I could show you on the live site - I can give you the link via email.thanks for any help
csbourne
@csbourne - Sure send me a link, nrcraver, gmail, should be eqasy to tweak it :)
Nick Craver
@Nick - I've sent over link to example site. Any ideas for a fix? Many thanks.
csbourne