Search code examples
jquerywrapall

How to wrap a certain number of divs in another div?


What's the best way to wrap a certain number of divs into another div? For example if I have 19 divs, how do I use wrapAll to group 9 of them and still group them even if it's under 9.

This is what I have now. It works if it's 4 but when I tried to do more, it would duplicate content from other elements.

$(".emails .multi-items").each(function (i) {
 var line_wrap = $(".line_wrap");
 for(var i=-1; i<line_wrap.length; i=i+5) {
  $('.line_wrap:eq('+i+'),.line_wrap:eq('+(i-1)+'),.line_wrap:eq('+(i-2)+'),.line_wrap:eq('+(i-3)+'),.line_wrap:eq('+(i-4)+')').wrapAll('<div class="wrap">');
  }
});

Solution

  • Here's a simple example:

    var size = 10; //define how many elements you want in each wrapper
    var items = $('.item'); //the collection of all your items
    var container; //this will be used to add the items in it.
    
    $.each(items, function(i, item) { 
      //this expression checks if we need to create a new container
      if (i % size === 0) {
        container = $('<div class="wrapped"></div>'); //create a new container
        $('body').append(container); //add the new container to the body
      }
      $(item).appendTo(container); //add the item to the container
    });
    .wrapped {
      border: 1px solid #ff0000;
      margin-bottom: 20px;
      padding: 20px;
    }
    
    .item {
      border: 1px solid #000000;
      width: 100%;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
    <div class="item">10</div>
    <div class="item">11</div>
    <div class="item">12</div>
    <div class="item">13</div>
    <div class="item">14</div>
    <div class="item">15</div>
    <div class="item">16</div>

    ---- AN EDIT FOLLOWING YOUR COMMENT

    Before running my code, this is what you get

    enter image description here

    You can just wrap the content of .message-contain

    If you want to run my code for every .message-contain PS: you have multiple id="content". Id's must be unique. You will run into problems if you keep the same id.

    PS2: You need to adapt the code to your example. You can't simply copy-paste into your code and expect it to work. I'm appending directly to the body which is not what you need. It was just an example.

    Here's an example of what I think you're trying to achieve.