Matthew Grima
Matthew Grima

Reputation: 1523

jQuery addClass for alternating levels of child elements

Say I have this html

<div class="details">
    <div class="details">
        <div class="details">
            <div class="details"></div>
            <div class="details"></div>
        </div>        
        <div class="details">
            <div class="details"></div>
            <div class="details"></div>
        </div>
    </div>
</div>

Without knowing the number of levels i'll have, is there a way I can add a class to every other level?

This would be the desired outcome:

<div class="details">
    <div class="details alternate">
        <div class="details">
            <div class="details alternate"></div>
            <div class="details alternate"></div>
        </div>        
        <div class="details">
            <div class="details alternate"></div>
            <div class="details alternate"></div>
        </div>
    </div>
</div>

EDIT I know such questions are frowned upon since it seems that I've not tried anything. But I have no idea what to look for

UPDATE Updated the html to show that there could be multiple details divs on the same level

Upvotes: 1

Views: 343

Answers (3)

Alnitak
Alnitak

Reputation: 339816

This works, albeit putting the alternate class on the first level and subsequent odd levels, rather than second and even:

$('.details').addClass(function() {
    if (!$(this.parentNode).hasClass('alternate')) {
         return 'alternate';
    }
});

You could use this instead which marks both the even and odd levels:

$('.details').addClass(function() {
    return $(this.parentNode).hasClass('odd') ? 'even' : 'odd';
});

See http://jsfiddle.net/P4ggZ/2/

Upvotes: 4

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382160

1) pure CSS solution :

I suppose your number of levels has a maximum, so you could use

body > .details { }
body > .details > .details { }
body > .details > .details  > .details { }
...

But this might get heavy if the style is big. In this case you'd better use a format allowing mixins to build your css (for example less).

2) jQuery solution (following question edit) :

If you want to do add a style in jQuery, you might do

function changeChilds($elems, depth) {
   if (!$elems.length) return;
   if (depth%2) $elems.addClass('alternate');
   changeChilds($elems.children('.details'), depth+1);
}
changeChilds($('body > .details'), 0);

Demonstration

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

You can use the number of .details parents each element has, and if it is an even number apply the .alternate class

$('.details').filter(function(){
    return ($(this).parents('.details').length % 2) === 0;
}).addClass('alternate');

Demo at http://jsfiddle.net/Ltn2j/1/

Upvotes: 3

Related Questions