Question

I need to wrap every third instance of a <div> in some HTML dynamically, and, if there is a remainder, to wrap that less-than-three amount in a similar manner, so it would serve as the last instance of the "wrap".

Getting every third instance wrapped is pretty basic:

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

However, because there is a remainder of 1 in this example, and I am otherwise dynamically generating HTML elsewhere (too complex to demo here, but that aspect works fine), the result in this example creates four .classwrap divs wrapping sets of three .someclass divs, giving me twelve .someclass divs, but not ten, however.

What I'm trying to achieve in this example is indeed four sets of .classwrap divs, but with the first three of those wrapper sets each containing three .someclass divs, and then getting a fourth .classwrap div that contains only one .someclass div, for the grand total of ten .someclass divs, as indicated by the limit variable.

I have tried to sneak in a modulus operator somewhere in my loop but it always throws off the math and wrapping accordingly.

Was it helpful?

Solution

Here is the answer I think you are looking for. You need to determine when the last grouping is being made. then use the modo value to only wrap that many sections.

Updated fiddle

var divs = $(".someclass"); 
var limit = 10;//divs.length;
var grouper = 3
var modo = limit % grouper;
for(var i = 0; i < limit; i+=grouper) {
    var offset = grouper;
    if(modo + i === limit) {
        offset = modo;
    }
    divs.slice(i, i+offset).wrapAll("<div class='classwrap' style='background-color:#def;'></div>");
}

OR

replace your initial selection with: Fiddle for slice

var limit = 10;
var divs = $(".someclass").slice(0,limit); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top