title: jquery add or slice
body: <p>I am trying to wrap a certain number of elements in a <code>div</code>. The problem is that the number of elements can vary based on the user's input. So the number of elements could be 2, 3, 4, or even more. I have a variable that tells me how many elements should be wrapped. So, for instance, my page may have this:</p>
  
  <pre><code>&lt;div class="test"&gt;&lt;/div&gt;
  &lt;div class="test"&gt;&lt;/div&gt;
  &lt;div class="test"&gt;&lt;/div&gt;
  &lt;div class="test"&gt;&lt;/div&gt;
  &lt;div class="test"&gt;&lt;/div&gt;
  &lt;div class="test"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>Now I need to wrap those in another <code>div</code> based on my variable. So, if my variable held a value of 3, it would look like this:</p>
  
  <pre><code>   &lt;div class="testing"&gt; 
      &lt;div class="test"&gt;&lt;/div&gt;
      &lt;div class="test"&gt;&lt;/div&gt;
      &lt;div class="test"&gt;&lt;/div&gt;   
     &lt;/div&gt;
  
     &lt;div class="testing"&gt;
      &lt;div class="test"&gt;&lt;/div&gt;
      &lt;div class="test"&gt;&lt;/div&gt;
      &lt;div class="test"&gt;&lt;/div&gt;
     &lt;/div&gt;
  </code></pre>
  
  <p>I was using this code:</p>
  
  <pre><code>$(this).add($(this).next())
         .add($(this).next().next())
         .wrapAll('&lt;div class="testing"&gt;&lt;/div&gt;');
  </code></pre>
  
  <p>The problem with that is that I would need to know how many elements are going to be there. Is there a dynamic way to do this? I also saw the <code>slice</code> function and tried to use it like this:</p>
  
  <pre><code>for(var i=0;i&lt;img_cnt;i+=img_row){
      obj.children().slice(i,i+img_row).wrapAll('&lt;div class="row"&gt;&lt;/div&gt;');
  }
  </code></pre>
  
  <p>It is not working, though. I have 8 <code>div</code>s. It should be wrapping 3 together, so I should have 3 new <code>div</code>s with 3 in the first 2 and 2 in the last, since there are only 8 <code>div</code>s. However, I get 3 <code>div</code>s in the first new <code>div</code>, then the next 2 <code>div</code>s are not wrapped at all, and then the last 3 <code>div</code>s are wrapped in a new <code>div</code>. I am not sure why it is not wrapping it right.  Do you have any ideas on how to do this or maybe even a better method?</p>