0

Is it possible to create this kind of loop?

For example : Wrap every 2 divs into a div, then (after 2 wrap) wrap every 3 divs (for 3 wrap)

<div id="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>

to

<div id="container">
<div class="group">
<div></div>
<div></div>
</div>
<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 class="group">
<div></div>
<div></div>
<div></div>
</div>
<div class="group">
<div></div>
<div></div>
</div>
<div class="group">
<div></div>
<div></div>
</div>
</div>

I have already found the classic method on this topic

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

Any ideas please?

(I'm a beginner so sorry if i get it wrong)

Iriel
  • 33
  • 4

1 Answers1

0

The step as in i += step should be a variable 2, and you should increment it on each iteration:

var divs = $("div > div");
var step = 1; // the step 
for (var i = 0; i < divs.length; i += step) { // increment i with the step
  divs.slice(i, i + step + 1).wrapAll("<div class='group'></div>"); // slice for i to i + step + 1 and wrap
  step++; // increment the step
}
.group:nth-child(even) {
  background: lightblue;
}

.group:nth-child(odd) {
  background: lightgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
  <div>11</div>
  <div>12</div>
  <div>13</div>
  <div>14</div>
  <div>15</div>
  <div>16</div>
  <div>17</div>
</div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Thank you for your reply ! I'm trying to apply your solution but I'm not familiar with this. My divs fit into each other. Can you explain the different variables? Or show an example with two steps? – Iriel Jul 19 '17 at 18:44
  • The only difference between this and your code, is the step variable (instead of the fixed step - 3) which is incremented. I've added comments in the code. – Ori Drori Jul 19 '17 at 18:46