Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all LI elements in array

Tags:

javascript

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")?

like image 666
Diesal11 Avatar asked Oct 26 '10 00:10

Diesal11


People also ask

How do you get all the li elements?

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. to call document. getElementById("navbar") to get the div element.

How do you get all Li in UL?

In JavaScript, you can use the . getElementsByTagName() method to get all the <li> elements in <ul>. In-addition, you can use the . querySelectorAll() method also to get all the <li>.

How to get li length in JavaScript?

log(document. getElementById("ul_o"). getElementsByClassName("LI"). length);

How to get selected li value in JavaScript?

Now, you want to get the content of the li element that was clicked. Since you bound the event handler to the ul element, this will always refer to the ul element inside the event handler. But you can get the element which triggered the event by accessing the target (or srcElement (IE)) property of the event object.


2 Answers

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.

like image 121
Nick Craver Avatar answered Sep 21 '22 11:09

Nick Craver


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>
like image 43
trincot Avatar answered Sep 17 '22 11:09

trincot