Devima
Devima

Reputation: 1566

Wrap div inside div from array values

First of all Hello to everyone, and sorry for my English.
I have ten divs an i want wrap them in groups inside a div with class="group"
The amount of div inside various divs. group depends on the values in an array
So if array is:[2,3,4,1] the result would be:

<div class="group">
    <div></div>
    <div></div>
</div>    

<div class="group">      
    <div></div>
    <div></div>
    <div></div>
</div>    

<div class="group">       
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

<div class="group">      
    <div></div>
</div>

I am able to get the desired result having an array that specifies the closing position of the different tag group [2,5,9,10]
But since today my brain doesn't seem works, i'm not able to achieve the same result with the first array [2,3,4,1].
Any answer will be read with pleasure, thank you all. code with second array:

var ranges=[2,5,9,10]
    for(i=0;i<ranges.length;i++){
        var a=0
        var b=0
        if(ranges[i]===2){ a=0; b=2}
        else{a=ranges[i-1]; b=ranges[i]}
        console.log(a,b)
        divs.slice(a, b).wrapAll("<div class='group'></div>");
        }

Upvotes: 0

Views: 199

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

You can use a start variable and a loop like this

var $divs = $('div'),
    start = 0;
$.each(array, function (i, val) {
    $divs.slice(start, start + val).wrapAll('<div class="group" />');
    start += val;
})

Demo: Fiddle

Upvotes: 1

Related Questions