0

I have code that look like this:

<div class="items">
   <div class="col"></div>
   <div class="col"></div>
   <div class="col"></div>
   <div class="col"></div>
   <div class="col"></div>
   <div class="col"></div>
   <div class="col"></div>
   <div class="col"></div>
</div>

I want to add row after 3 col that the final result will be:

<div class="items">
   <div class="row">
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
   </div>
   <div class="row">
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
   </div>
   <div class="row">
      <div class="col"></div>
      <div class="col"></div>
   </div>
</div>

I must do this using jQuery. The number of col's is not constant. Please help

2 Answers2

2

Assuming by "the number of col's is not constant", you are referring to the total amount, and not how many columns should be in each row.

The following assumes there should be a maximum of 3 columns in a row:

$(function(){

    $(".col").each(function(i,v){
        var $row;
        if ((i % 3) == 0){
           $row = $("<div/>");
            $row.addClass("row");
            $(".items").append($row);
        }
        else
        {
            $row = $(".items .row:last");   
        }
        $row.append($(this));
    });

});

--- See Live Demo ---

Curtis
  • 101,612
  • 66
  • 270
  • 352
0

You should have a look on $('selector').each() at

http://api.jquery.com/each/

With this function you are able to iterate through your items-div.

Pseudo-Code:

$('.items .col').each(function(index) {

  // index is a counter helping you

  // $(this) is the element at the current index

  // the rest is just logical thinking

});
Kimtho6
  • 6,154
  • 9
  • 40
  • 56
tellob
  • 1,220
  • 3
  • 16
  • 32