'old is gold. But, is there any better way to do it? [closed]
Hello there I have an unordered list. I wanted to loop through the li elements. But, for my lack of knowledge I failed to use es6 for that. I got my result using for loop. But, I want to know is there any better way to do it? Please let me know.
<ul id="product-nav-ul">
<li id="first">All</li>
<li id="second">Oranges</li>
<li id="third">Fresh Meat</li>
<li id="fourth">Vegetables</li>
<li id="fifth">Fastfood</li>
</ul>
const productNavUl = document.getElementById('product-nav-ul');
let lis = productNavUl.children;
console.log(productNavUl.children)
console.log(lis.length)
for(let i = 0; i<lis.length; i++){
console.log(lis[i].id)
}
Solution 1:[1]
This depends on what you want to do with the li elements. If you want to just retrieve the id, i think the most 'modern' approach would be using map.
const liIds = Array.from(productNavUl.children).map((li) => li.id)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mgottsch |
