I try do number all links in a nested list, the number should go in the “data-nav-no” attribute, the result should be like this:
<ul class="mainNav">
<li><a href="#startseite" data-nav-no="1">Startseite</a></li>
<li><a href="#ueber-uns" data-nav-no="2">Über uns</a></li>
<li><a href="#leistungen" data-nav-no="3">Leistungen</a>
<ul class="subNav">
<li><a href="#langfristige-unterstuetzung" data-nav-no="4">Langfristige Unterstützung</a></li>
<li><a href="#punktuelle-unterstuetzung" data-nav-no="5">Punktuelle Unterstützung</a></li>
</ul>
</li>
<li><a href="#referenzen" data-nav-no="6">Referenzen</a></li>
<li><a href="#news" data-nav-no="7">News</a></li>
<li><a href="#kontakt" data-nav-no="8">Kontakt</a></li>
</ul>
I tried this:
$("ul.mainNav li, ul.subNav li").each(function() {
var index = $(this).index();
$(this).children("a").attr('data-nav-no',index);
});
Works, but in the second list level the number starts with “0” again. Any ideas to solve that?
The following should do what you want:
The selector
ul.mainNav liis finding alllis that are descendants oful.mainNav; which includes the elements matched by the selectorul.subNav li. This is why I’ve omitted theul.subNav liselector from my example. If you want to only target the children of theul.mainNavelement, then you should use the child selector instead of the descendant:The
.index()method you were using returns the position of the element relative to it’s sibling elements, where-as theindexparameter provided by.each()is the position of the element in the jQuery collection.