Reputation: 169
I'm trying to add a different class to elements within an each statement if certain conditions are true. Here is the code:
$('.horizontal').each(function() {
if($(this).children().size() == 3){
console.log('the number 3')
$('.horizontal > div').addClass('span4');
}
if($(this).children().size() == 6){
console.log('the number 6')
$('.horizontal > div').addClass('span2');
}
});
The problem is that I'm setting everything with the last if statement rather than independently assigning a class based on the output. So, if I have an element that has 3 children and then one later on that has 6, they both get 'span2' applied. Any help is appreciated.
Upvotes: 0
Views: 410
Reputation: 253358
Why not:
$('.horizontal').children().addClass(function(){
switch ( $(this).parent().children().length ) {
case 3:
return 'span4';
break;
case 6:
return 'span2';
break;
}
});
Alternatively, to iterate over the parents, rather than all of the children (which, admittedly, was an expensive solution):
$('.horizontal').each(function(){
var self = $(this),
newClass;
switch (self.children().length) {
case 6:
newClass = 'span2';
break;
case 3:
newClass = 'span4';
break;
default:
newClass = '';
break;
}
self.children().addClass(newClass);
});
Or even:
var classes = {
'3' : 'span4',
'6' : 'span2'
};
$('.horizontal').each(function(){
var self = $(this),
kids = self.children();
kids.addClass(classes[kids.length] || '');
});
References:
Upvotes: 3
Reputation: 1433
Your selector $('.horizontal > div')
selects all divs inside a element with class 'horizontal', not just the ones with 6 children. On both of those, you probably want $(this).children('div').addClass('spanWhatever');
Upvotes: 3