featherz
featherz

Reputation: 169

Want to set a class for each element if certain conditions are true

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

Answers (2)

David Thomas
David Thomas

Reputation: 253358

Why not:

$('.horizontal').children().addClass(function(){
    switch ( $(this).parent().children().length ) {
        case 3:
            return 'span4';
            break;
        case 6:
            return 'span2';
            break;
    }
});

JS Fiddle proof-of-concept.

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);
});

JS Fiddle proof-of-concept.

Or even:

var classes = {
    '3' : 'span4',
    '6' : 'span2'
};

$('.horizontal').each(function(){
    var self = $(this),
        kids = self.children();
    kids.addClass(classes[kids.length] || '');
});

JS Fiddle proof-of-concept.

References:

Upvotes: 3

Jordan
Jordan

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

Related Questions