Try this code:
$('ul.level2').each(function(i){
$(this).addClass('count'+i.toString());
});
题
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.
<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>
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{
}
解决方案
Try this code:
$('ul.level2').each(function(i){
$(this).addClass('count'+i.toString());
});
其他提示
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");
});