Reputation: 678
I have a menu and pretty much each item in it has a submenu. the menu system is structured like this
<div id="leftNav">
<ul class="level1">
<li><a href="#">Link1</a>
<ul class="level2" id="submenu01">
<li class="deptName"><a href="#">Link1</a></li>
<li><a href="#">Link1.1</a></li>
<li><a href="#">Link1.2</a></li>
<li><a href="#">Link1.3</a></li>
</ul>
</li>
<li><a href="#">Link2</a>
<ul class="level2" id="submenu02">
<li class="deptName"><a href="#">Link2</a></li>
<li><a href="#">Link2.1</a></li>
<li><a href="#">Link2.2</a></li>
<li><a href="#">Link2.3</a></li>
</ul>
</li>
</ul>
</div>
where .level2 is the submenu. I need to add a class to each anchor in the submenu, except for the anchor in the li with the deptName class. this is easy enough, but, i need the class to be "levelTwoLinkXX" where "XX" is the 01 for the first, 02 for the second and so on. Then this needs to happen for each level2 starting back at levelTwoLink01 for the first link not in the deptName class.
The javascript I came up with is:
$(function(){
$('.level2 > li:not('.deptName') > a').each(function(){
$(this).addClass('levelTwoLink0' + (index+1));
});
});
the problem is that it starts at 01 and by the time it assigns the class to #submenu02 the index is at 4. How would i go about getting it to restart for each new submenuXX?
Upvotes: 0
Views: 943
Reputation: 985
Something like that?
$("li ul").each(function(i, e) {
$("li:not('.deptName') a", this).addClass("levelTwoLink" + this.id.replace(/\D*/,''));
});
Upvotes: 0
Reputation: 2232
Your jQuery expression is incorrect. You're closing the jQuery String when adding the deptName class selector.
Also the each function can take a parameter that represents the index of the current element in the DOM. The correct code should then be:
$('ul.level2').each(function() {
$(this).find('li:not(.deptName) a').each(function(index){
$(this).addClass('levelTwoLink0' + ( index + 1 ));
});
});
What you need to do is first loop through the level2 first then through each li inside.
Upvotes: 0
Reputation: 235982
$('ul.level2').each(function() {
$(this).find('li').not('.deptName').each(function(i) {
$(this).find('a').addClass('levelTwoLink0' + (i+1));
});
});
Demo: http://www.jsfiddle.net/DAunT/3/
Upvotes: 1