Reputation: 987
I want to stack divs one after another, by class, so if div has class of "icon1" then the following div will be "icon2". I want to to id within the each loop.. to prevent multiple Dom manipulations
var arr = [{
"id": 1,
"name": "foo"
}, {
"id": 1,
"name": "foo"
}, {
"id": 2,
"name": "foo"
}, {
"id": 1,
"name": "foo"
}];
var type = '';
var template ='';
$.each(arr, function() {
if (this['id'] == 1) {
type = 'icon1';
} else {
type = 'icon2';
}
template += '<div class="icon '+type+'">'+
'<p>ID: '+type+' Name: '+this['name']+'<p></div>';
});
$('#foo').html(template);
.icon1 {
color: red;
}
.icon2 {
color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
</div>
The result i'm looking for will be :
icon1
icon2
icon1
icon2
icon1
icon2
etc...
Upvotes: 2
Views: 124
Reputation: 376
This is a solution:
var array = [
{
"id": 1,
"name": "foo"
},
{
"id": 1,
"name": "foo"
},
{
"id": 2,
"name": "foo"
},
{
"id": 1,
"name": "foo"
}
];
var lsts = [ [], [] ];
$.each( array, function() {
lsts[ this.id - 1 ].push( this );
} );
var lst1 = lsts[ 0 ],
lst2 = lsts[ 1 ];
for ( var i = 0, l = lst1.length, l2 = lst2.length; i < l || i < l2; i++ ) {
if ( i < l )
appendElement( lst1[ i ] );
if ( i < l2 )
appendElement( lst2[ i ] );
}
function appendElement( obj ) {
$( '#bar' ).append( '<div class="icon' + obj.id + '">' + obj.name + '</div>' );
}
.icon1 {
color: red;
}
.icon2 {
color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bar"><div>
Beware of another ID numbers.
Upvotes: 1
Reputation: 1635
You can use css nth-child property to get this styles
div:nth-child(odd) {
color: red;
}
div:nth-child(even) {
color: pink;
}
Upvotes: 1