Reputation: 922
I am trying to get different classes for each ul li as mentioned below in code. The code I have tried so far is in jQuery, But I need this to be achieved in vanilla Javascript
Any help will be appreciated !!
const topLevel = Array.from(document.querySelector(".main-nav-list > li > ul"))
.map(({
parentElement
}) => parentElement);
for (const element of topLevel) {
element.setAttribute(`${element.className} hasChild top`);
const subLevel = Array.from(element.querySelectorAll("li > ul"))
.map(({
parentElement
}) => parentElement);
for (const subElement in subLevel) {
subElement.setAttribute(`${subElement.className} hasChild sub`);
}
}
<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>
<li class="c"> <a href="/">Winter</a> </li>
<li class="c"> <a href="/">All season</a> </li>
<li class="c"> <a href="/">Spring </a> </li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
Upvotes: 1
Views: 174
Reputation: 467
This is how you could achieve this in vanilla JavaScript, the details of it are a bit complicated and don't really fit in an answer, because each of these methods used here and the jQuery ones you used above all have specific behaviours and backgrounds which are further explained in the respective documentations:
const topLevel = Array.from(document.querySelector(".main-nav-list > li > ul"))
.map(({parentElement}) => parentElement);
for (const element of topLevel) {
element.setAttribute(`${element.className} hasChild top`);
const subLevel = Array.from(element.querySelectorAll("li > ul"))
.map(({parentElement}) => parentElement);
for (const subElement of subLevel) {
subElement.setAttribute(`${subElement.className} hasChild sub`);
}
}
Upvotes: 1