Multiple Methods to Retrieve All LI Elements Inside a UL and Convert Them to an Array in JavaScript

Dec 07, 2025 · Programming · 9 views · 7.8

Keywords: JavaScript | DOM Manipulation | Array Conversion

Abstract: This article provides an in-depth exploration of how to efficiently retrieve all LI elements within a UL element in JavaScript and convert them into a manipulable array. It begins by introducing the traditional getElementsByTagName() method, which returns a NodeList object—similar to an array but not a true array. The article then delves into the characteristics of NodeList, including its length property and iteration methods. Subsequently, it supplements with modern JavaScript (ES6 and above) techniques, such as Array.from() and the spread operator, which enable direct conversion of NodeList into genuine arrays, offering more flexible iteration and manipulation. Through code examples and comparative analysis, the article helps readers understand the applicable scenarios and performance differences of various methods, aiming to provide comprehensive technical reference for front-end developers.

Traditional Method: Using getElementsByTagName()

In JavaScript, retrieving DOM elements is a common task in front-end development. For the question "how to get all LI elements inside a UL and put them into an array," a classic solution is to use the getElementsByTagName() method. For example, given the following HTML structure:

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

We can retrieve all LI elements with the following code:

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

Here, getElementById("navbar") first locates the DIV element with ID "navbar," and then getElementsByTagName("li") returns a collection of all LI elements within that DIV. It is important to note that this method returns a NodeList object, not a true JavaScript array. NodeList is an array-like object that has a .length property and allows indexed access to elements, e.g., lis[0] returns the first LI element (i.e., document.getElementById("navbar-One")). However, NodeList does not support all array methods, such as push() or forEach() (though some browsers may support them, it is non-standard).

Characteristics and Iteration of NodeList

Although NodeList resembles an array, it is essentially a dynamic collection of DOM nodes. This means that if the DOM structure changes (e.g., adding or removing LI elements), the NodeList automatically updates to reflect these changes. When iterating over a NodeList, a traditional for loop can be used:

for (var i = 0; i < lis.length; i++) {
    console.log(lis[i].textContent); // Outputs the text content of each LI
}

Alternatively, in modern browsers, the forEach() method can be used (if supported by NodeList), but for compatibility, it is advisable to convert it to an array first. Additionally, NodeList is "live," which in some scenarios may cause performance issues because each access re-queries the DOM. Therefore, if frequent manipulation is required, converting it to a static array might be more efficient.

Modern Methods: Using Array.from() and the Spread Operator

With the introduction of ECMAScript 6 (ES6), JavaScript offers more elegant ways to convert NodeList to an array. One method is using the Array.from() function:

const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));

Here, document.querySelectorAll('#navbar>ul>li') uses a CSS selector to retrieve all matching LI elements, returning a NodeList. Array.from() converts it into a true array, enabling the use of all array methods, such as map(), filter(), or reduce(). For example, to extract the text content of all LIs:

const texts = navbar.map(li => li.textContent);
console.log(texts); // Outputs: ["One", "Two", "Three", "Four", "Five"]

Another method is using the spread operator:

const navbar = [...document.querySelectorAll('#navbar>ul>li')];

This also converts the NodeList to an array, with more concise code. Furthermore, Array.from() accepts an optional mapping function as a second parameter, allowing direct processing of elements during conversion:

Array.from(document.querySelectorAll('#navbar>ul>li'), li => console.log(li.textContent));

For iteration, modern JavaScript recommends using a for...of loop, which can directly iterate over NodeList or arrays:

for (const li of document.querySelectorAll('#navbar>ul>li')) {
    console.log(li.textContent);
}

Comparison and Selection Recommendations

When choosing a method, browser compatibility and project requirements must be considered. The traditional method (getElementsByTagName()) is compatible with all browsers, but returning a NodeList may limit operational flexibility. Modern methods (Array.from() or the spread operator) offer better array functionality but require ES6 support (not supported in IE11 and earlier). If the target environment supports ES6, it is recommended to use modern methods to improve code readability and maintainability. For performance-critical applications, if the DOM structure is stable, converting NodeList to a static array can reduce the overhead of dynamic queries. In summary, understanding these core concepts helps in efficiently handling collections of DOM elements in front-end development.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.