title: how to dynamically group every n-divs and wrap up with a new div in JQuery?
body: <p>I want to select every 4 divs with <code>class "contents"</code> and wrap it in another new div that is created dynamically using <code>Jquery</code>. my HTML is as follows;</p>
  
  <pre><code>&lt;body&gt;
  &lt;div id="postings"&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>I want </p>
  
  <pre><code>&lt;body&gt;
  &lt;div id="postings"&gt;
  &lt;div id="newDivforWraping1"&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
       &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;div id="newDivforWraping2"&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;div id="newDivforWraping3"&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
      &lt;div class="contents"&gt;&lt;/div&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>my current JScript code is below;</p>
  
  <pre><code>(function() {
      "use strict";
      $(document).ready(function() {
          insertdiv("newDivforWraping1",4);
          insertdiv("newDivforWraping2",8);
          insertdiv("newDivforWraping3",12);
          });
  
          //create div for every grouping them into three
          function insertdiv(divname,n) {
              $("&lt;div/&gt;", {class: "test",id:divname}).appendTo("#postings");
              var allcontentspost = $(".contents").each();
              for (var i=n-4;i&lt;n;i++) {
                  allcontentspost[i].appendTo("#"+divname);
              };
          }
  })();
  </code></pre>