I have a simple navigation with two levels. The li-elements of the first level shall get class="n11", that of the second class="n12".
This will write class="n11" to every li-element.
var firstNavi = document.getElementsByClassName("nav1-1");
for(var i = 0; i < firstNavi.length; i++) {
var firstLi = firstNavi[i].querySelectorAll("li");
for(var i = 0; i < firstLi.length; i++) {
firstLi[i].classList.add("n11");
}
}
<ul class="nav1-1">
<li ><a href="">1.1.</a></li>
<li ><a href="">1.2</a>
<ul class="nav1-2">
<li><a href="">1.2.1</a></li>
<li><a href="">1.2.2</a></li>
</ul>
</li>
<li><a href="">1.3</a>
<ul class="nav1-2">
<li><a href="">1.3.1</a></li>
<li><a href="">1.3.2</a></li>
</ul>
<li><a href="">1.4</a></li>
</ul>
How to achieve that is written class="n12" to the second li-elements and class="n11" only to the first level entries? Thanks for any help.
You can just retrieve the first level <li> elements as well as the second level <li> elements by using the child combinator > on the first level parent <ul> element and the second level <ul> parent element and now you can just loop through each list element and add the class name accordingly like this:
const firstLevel = document.querySelectorAll('.nav1-1 > li');
const secondLevel = document.querySelectorAll('.nav1-2 > li');
for (var i = 0; i < firstLevel.length; i++) {
firstLevel[i].classList.add('n11');
}
for (var i = 0; i < secondLevel.length; i++) {
secondLevel[i].classList.add('n12');
}
<ul class="nav1-1">
<li ><a href="">1.1.</a></li>
<li ><a href="">1.2</a>
<ul class="nav1-2">
<li><a href="">1.2.1</a></li>
<li><a href="">1.2.2</a></li>
</ul>
</li>
<li><a href="">1.3</a>
<ul class="nav1-2">
<li><a href="">1.3.1</a></li>
<li><a href="">1.3.2</a></li>
</ul>
<li><a href="">1.4</a></li>
</ul>
If you do not care about IE 11 compatibility or you are using a JavaScript compiler like Babel, you can further shorten and simplify the above JavaScript by using the forEach() method and arrow functions like this:
const firstLevel = document.querySelectorAll('.nav1-1 > li');
const secondLevel = document.querySelectorAll('.nav1-2 > li');
firstLevel.forEach(e => e.classList.add('n11'));
secondLevel.forEach(e => e.classList.add('n12'));
<ul class="nav1-1">
<li ><a href="">1.1.</a></li>
<li ><a href="">1.2</a>
<ul class="nav1-2">
<li><a href="">1.2.1</a></li>
<li><a href="">1.2.2</a></li>
</ul>
</li>
<li><a href="">1.3</a>
<ul class="nav1-2">
<li><a href="">1.3.1</a></li>
<li><a href="">1.3.2</a></li>
</ul>
<li><a href="">1.4</a></li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With