How to Get All li Elements in an Array with JavaScript?

Sometimes, we want to get all li elements in an array with JavaScript.

In this article, we’ll look at how to get all li elements in an array with JavaScript.

Get All li Elements in an Array with JavaScript

To get all li elements in an array with JavaScript, we can call the getElementsByTagName method to get all the li elements.

Then we can use the spread operator to spread all the items in the node list to an array.

For instance, if we have:

<div id="navbar">
  <ul>
    <li id="navbar-One">One</li>
    <li id="navbar-Two">Two</li>
    <li id="navbar-Three">Three</li>
    <li id="navbar-Four">Four</li>
    <li id="navbar-Five">Five</li>
  </ul>
</div>

then we write:

const lis = [...document.getElementById("navbar").getElementsByTagName("li")];
console.log(lis)

to call document.getElementById("navbar") to get the div element.

Then we can select the li elements inside with .getElementsByTagName("li").

Next, we use the spread operator to spread all the returned li elements into an array an assign it to lis.

Therefore, we should see that lis is an array with the 5 li elements in the console log.

Conclusion

To get all li elements in an array with JavaScript, we can call the getElementsByTagName method to get all the li elements.

Then we can use the spread operator to spread all the items in the node list to an array.