Pergunta

i´ve got a 3 lvl navigation and i want that every "ul" with the class "levle2" get an additional class called "count" with a counter that counts the "ul´s" and puts the number behind the class.

This is how it should look like

<ul class="level1" >
        <li>
            <a href="#">More options</a>
            <ul class="level2 count1">
                <li><a href="#">Second level link</a></li>
                <li><a href="#">Second level link</a></li>

            </ul>
        </li>
            <li>
            <a href="#">More options2</a>
            <ul class="level2 count2">
                <li><a href="#">Second level link2</a></li>
                <li><a href="#">Second level link2</a></li>

            </ul>
        </li>
    <li>
            <a href="#">More options3</a>
            <ul class="level2 count3">
                <li><a href="#">Second level link3</a></li>
                <li><a href="#">Second level link3</a></li>

            </ul>
        </li>
</ul>

JS Code

if($('ul.level1 li').find('ul').children('ul.level3').length > 0)
{
    var item = $('ul.level1 li').find('ul').children('ul.level3');
    item.parent().addClass('count');
} else{

}

http://jsfiddle.net/HvPtW/9/

Foi útil?

Solução

Try this code:

$('ul.level2').each(function(i){
    $(this).addClass('count'+i.toString());
});

Outras dicas

For select every object with a specifique className and add to each object wich contains className look at your console:

var allElmtsClassName = $(".className");
allElmtsClassName.each(function(index)
{
   console.log(index);
   $(this).addCLass("anotherCLass");
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top