Search code examples
jqueryhtmlappenddetach

Append only 4 divs and the remaining divs in another section


Say there is a section with 12 divs. I'm trying to append 4 divs at a time into into a new section (container). So there will be 4 divs appended in the first section, then 4 divs appended to a different second section, then 4 divs to a third section, and so on.

Beginner wordpress/jQuery coder here; I would greatly appreciate explanations :) Open to other approaches but I'd like to have these 3 functions:

1) some counting mechanism so that a section holds only up to 4 divs

2) if there are more than 4 divs (say 6) a new section created to house the remaining 2

3) adding the divs that have not already been added.

Starting with 12 divs in a section:

  <section>
      <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>
  </section>

after the JQuery, I'd like the divs appended to be organized as:

 <section id="FirstSection">
      <div> 1 </div>
      <div> 2 </div>
      <div> 3 </div>
      <div> 4 </div>
  </section>
  <section id="SecondSection">
      <div> 5 </div>
      <div> 6 </div>
      <div> 7 </div>
      <div> 8 </div>
  </section>
  <section id="ThirdSection">
      <div> 9 </div>
      <div> 10 </div>
      <div> 11 </div>
      <div> 12 </div>
  </section>

Solution

  • I hope this code works for you. I also made a demo here.

    <section>
        <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>
    </section>
    <div id="main"></div>
    <script>
        var div_count = 0;
        var section_count = 0;
    
    $('div[id!="main"]').each(function () {
      if ($("#section-"+section_count).length == 0) {
        $('#main').append('<section id="section-'+section_count+'"></section>');
      }
    
      $("#section-"+section_count)[0].append($(this).html());
      $(this).remove();
    
      div_count += 1;
    
      if (div_count > 3) {
        div_count = 0;
        section_count += 1;
      }
    });
    </script>