0

Because of formatting reasons I'm trying to nest every third result from my json file to be nested in a div class "row".

I figured this would be an easy thing to do but everytime I try jQuery closes my tags.

Proper layout should be

<div class="row">
   <div class="four columns"></div>
   <div class="four columns"></div>
   <div class="four columns"></div>
</div>

Here is my code:

var sexIcon = '';
var typeIcon = '';
var divClassRow = '  <div class="row">  ';
var divClassRowEnd = '  </div><div class="row">  ';
$(document).ready(function(){

    $.getJSON("scripts/pets.json", function(jsonData){
        $.each(jsonData, function(object, value){
            if (value.sex=='female'){
                sexIcon = 'images/female-active.png';
            }
            else {
                sexIcon = 'images/male-active.png';
            };
            if (value.type=='dog'){
                typeIcon = 'images/dog-sm.png';
            }
            else {
                typeIcon = 'images/cat.png';
            }
            $('.columns:first-child').before(divClassRow);
            $.each($('.columns:nth-child(4n)'), function(){
                $(this).after(divClassRowEnd);
            });


            $(".cards").append(

                '<div class="four columns '+ value.type +' '+ value.sex +' '+ value.size +'">'+
                '<div class="card-header"><h3>'+value.name+'</h3><img src="'+typeIcon+'" alt=""><img src="'+sexIcon+'" alt=""></div>'+
                '<div class="card-content">'+
                '<img src="'+value.photo+'" alt="">'+
                '<p><b>Breed:</b> '+value.breed+'</p>'+
                '<p><b>Sex:</b> '+value.sex+'</p>'+
                '<p><b>Age:</b> '+value.age+'</p>'+
                '<p><b>Time at Rescue:</b> '+value.time+'</p>'+
                '<p> '+value.about+'</p>'+
                '<br>'+
                '<button class="button-primary u-full-width">Find Out more!</button>'+
                '</div></div>'

                ); /*END APPEND*/
        });/*END EACH*/
    });/*END GETJSON*/


}); /* Document Ready */

Any ideas on what I can do? Or perhaps how to do this better.

Chris Stage
  • 187
  • 12
  • What is current result? Can you create a stacksnippets or jsfiddle http://jsfiddle.net to demonstrate? Tried calling second `$.each()` after conclusion of first `$.each()`? – guest271314 Apr 26 '16 at 04:27

1 Answers1

0

Use wrapAll()

var list=$('.four');
for(var i = 0; i < list.length; i+=4) {
  list.slice(i, i+4).wrapAll("<div class='row'></div>");
}

demo

madalinivascu
  • 32,064
  • 4
  • 39
  • 55