46

How can i make JS select every LI element inside a UL tag and put them into an array?

<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>

Can i make it so JS gets each of them into an array eg navbar['0'] would return document.getElementById("navbar-One")?

DimaSan
  • 12,264
  • 11
  • 65
  • 75
Diesal11
  • 3,389
  • 9
  • 28
  • 29

5 Answers5

78

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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 5
    It's important to emphasize: **This is not an array**. It will not behave like an array. If at any point you choose to remove an `LI` element from the HTML, its entry will be "popped" from the collection, everything above it will shift down to fill the space, and the `.length` will decrease. This is not a suitable solution for anyone looking to produce an `array`, and this can only be achieved by iterating through the elements or [converting it to an array](http://stackoverflow.com/questions/222841/most-efficient-way-to-convert-an-htmlcollection-to-an-array). – Super Cat Aug 10 '16 at 23:45
31

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>
trincot
  • 317,000
  • 35
  • 244
  • 286
  • an alternative but seems unnecessarily complex – CommonSenseCode Dec 12 '17 at 14:11
  • 3
    The accepted answer calls two DOM methods, while this solution only calls one. The accepted answer does not produce an Array instance, while this answer does, by adding a very readable `Array.from` (I mean: it says what it does, right?). So I don't see why this should be considered "complex". – trincot Jul 04 '19 at 18:39
9

QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li tag) to get all of the li present inside the div with navbar element.

    let navbar = document
      .getElementById("navbar")
      .querySelectorAll('li');

    navbar.forEach((item, index) => {
      console.log({ index, item })
    });
   
<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>
Vectrobyte
  • 1,408
  • 12
  • 30
1

If you want all the li tags in an array even when they are in different ul tags then you can simply do

var lis = document.getElementByTagName('li'); 

and if you want to get particular div tag li's then:

var lis = document.getElementById('divID').getElementByTagName('li'); 

else if you want to search a ul first and then its li tags then you can do:

var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
    var lis=uls[i].getElementsByTagName('li');
    for(var j=0;j<lis.length;j++){
        console.log(lis[j].innerHTML);
    }
}
1
var allElmnts = document.querySelectorAll("ul");
var arr = []; 
arr.length = allElmnts.length; 
for(var i = 0; i < allElmnts.length; i++){

    arr[i] = allElmnts[i]; 

}