Get all LI elements in array

After some years have passed, you can do that now with ES6 Array.from (or spread syntax):

const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));
console.log('Get first: ', navbar[0].textContent);

// If you need to iterate once over all these nodes, you can use the callback function:
console.log('Iterate with Array.from callback argument:');
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))

// ... or a for...of loop:
console.log('Iterate with for...of:');
for (const li of document.querySelectorAll('#navbar>ul>li')) {
    console.log(li.textContent);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<div id="navbar">
  <ul>
    <li id="navbar-One">One</li>
    <li id="navbar-Two">Two</li>
    <li id="navbar-Three">Three</li>
  </ul>
</div>

You can get a NodeList to iterate through by using getElementsByTagName(), like this:

var lis = document.getElementById("navbar").getElementsByTagName("li");

You can test it out here. This is a NodeList not an array, but it does have a .length and you can iterate over it like an array.

Tags:

Javascript