In my attempt to dynamically generate the class name within the ul
element, I successfully achieved the expected result. The outcome can be viewed in the console of the snippet provided for reference.
However, I'm facing a challenge when attempting to create the same class name for the ul
elements generated under a li
element. For instance, if there is a li
element with the class name "a"
, and multiple ul
elements are created under the same li
element, the class names of the ul
should remain consistent. Instead, the classes are being numbered sequentially.
The desired outcome is as follows:
<li class="a">
<a href="/">First</a>
<ul class="main-nav-list">
<li class="b">
<a href="/">Type of menu</a>
<ul class="main-nav-list ul-1">
<li class="c"><a href="/">Summer</a></li>
</ul>
</li>
<li class="b">
<a href="/">Type of menu</a>
<ul class="main-nav-list ul-1">
<li class="c"><a href="/">Summer</a></li>
</ul>
</li>
I have made an attempt to achieve this dynamic class generation:
var ul = document.querySelectorAll(".main-nav ul");
ul.forEach((each, i) => {
each.classList.add("ul-" + i);
console.log(each)
});
<nav class="main-nav">
<ul class="main-nav-list">
<li class="a">
<a href="/">First</a>
<ul class="main-nav-list">
<li class="b">
<a href="/">Type of menu</a>
<ul class="main-nav-list">
<li class="c"><a href="/">Summer</a></li>
</ul>
</li>
<li class="b">
<a href="/">Type of menu</a>
<ul class="main-nav-list">
<li class="c"><a href="/">Summer</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
If the first ul
has the class ul-0
, then subsequent ul
elements should also have ul-0
as their respective classes.
Any assistance on this matter would be greatly appreciated!