3

I have this:

<div class="myTest"></div>
<div class="myTest"></div>
<div class="myTest"></div>
<div class="myTest"></div>
<div class="myTest"></div>
<div class="myTest"></div>
<div class="myTest"></div>
<div class="myTest"></div>
<div class="myTest"></div>
<div class="myTest"></div>

and I am trying to get:

<div class="holder">
    <div class="myTest"></div>
    <div class="myTest"></div>
    <div class="myTest"></div>
    <div class="myTest"></div>
    <div class="myTest"></div>
</div>
<div class="holder">
    <div class="myTest"></div>
    <div class="myTest"></div>
    <div class="myTest"></div>
    <div class="myTest"></div>
    <div class="myTest"></div>
</div>

using jQuery. I have tried using nth-child, but then it wraps every element with that div instead.

I am trying to get every 5 elements into a div called holder.

Although that, I am trying to use "nth to nth" element approach. In other words, it is NOT an assumption that every 5 element is wrapped, but rather 1st-to-5th element wrapped in one div, and perhaps 6th-to-14th element in another. And let's assume these 2 batches are both wrapped with the same class, holder.

Any dynamic way to batch these up?

Sina
  • 765
  • 1
  • 13
  • 32

1 Answers1

4

You can do it by using each() and wrapAll(),

var tmp = $();
$(".myTest").each(function(i){
  tmp = tmp.add(this);
  if(((i+1) % 5) == 0){ 
    tmp.wrapAll("<div class='holder'>"); 
    tmp = $(); 
  }
});

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130