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")
?
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.
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>.
log(document. getElementById("ul_o"). getElementsByClassName("LI"). length);
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With