HTML Collection to Array
The most Effective Method for Changing an HTML Collection into an Array
Several DOM methods, such as "getElementsByTagName" and "querySelectorAll," return an HTMLCollection, which is an array-like collection of HTML elements. Nevertheless, this collection lacks the functionality of an array and is not an array itself. For this reason, to carry out some array-specific actions, it might be required to transform the HTMLCollection to an array. In this post, we'll look at every way to turn an HTMLCollection into an array.
Table of Content
- Using Array. prototype.slice( )
- Using Array.from()
- Using Spread Operator
- Using for-loop
Using Array.prototype.slice():
In this technique, Array.prototype.slice() is bound to the call() function. This will cause HTMLCollection to use Array.prototype.slice(), which transforms it into an array by making a shallow duplicate of the HTMLCollection. The syntax we'll use is listed below.
Syntax:
Array.prototype.slice.call(htmlCollection)
What is HTMLCollection Array?
First Solution:
It is an HTMLCollection rather than an Array.
It does not inherit from the Array prototype since it has Array-like attributes like numeric properties and an a.length property. As such, it is unique in that it lacks the conventional Array methods.
It is noteworthy that HTMLCollection is a dynamically updated collection that takes into account DOM changes. Upon removal from the DOM, a node is immediately deleted from HTMLCollection.
Option 2:
If you are thinking of converting an array, please read this post.
The best way to convert an HTMLCollection into an array.
Throughout the debate, many approaches were presented, and I discovered that the solution in the chosen response also addressed a problem similar to one I had faced.
How may HTMLCollection be iterated upon? [Repeated], Simply use the spread operator [Array.from(document.getElementsByClassName('node-item')) or the spread operator.
Why not just Turn Them into an Array?
To utilize higher-level methods like forEach, map, filter, and reduce, you must convert an HTMLCollection and NodeList to an array.
There are several applications. For example, suppose you have components with a data-src attribute and a lazy-load class. You may use the following to obtain the data-src and filter out all the items that are empty or lack data-src.
Use Case
var lazyLoadables = [...document.querySelectorAll('.lazy-load')]
.filter((element) => element.getAttribute('data-src').trim());
lazyLoadImages(lazyLoadables);
We ensured that only items with a source that must be loaded when necessary were sent by doing this.
<!DOCTYPE html>
<html>
<head>
<title>Example for HTMLCollection To Array Conversion</title>
</head>
<body>
<div>
<p>This is line 1</p>
<p>This is line 2</p>
<p>This is line 3</p>
</div>
<script>
const htmlCollection =
document.getElementsByTagName("p");
const array = Array.prototype
.slice.call(htmlCollection);
console.log(array);
</script>
</body>
</html>
Output
Using Array.from():
ES6 introduces the Array.from() function. This function creates a new array with the same items by taking an iterable object that resembles an array. In this instance, HTMLCollection is the array-like iterable object. All we have to do is feed it to this function, and it returns an array.
Syntax:
Array.from(htmlCollection)
Example: In this example, an HTMLCollection is converted to an Array in an HTML page using the Array.from() function.
<!DOCTYPE html>
<html>
<head>
<title>Example for HTMLCollection to Array Conversion</title>
</head>
<body>
<div>
<p>This is line 1</p>
<p>This is line 2</p>
<p>This is line 3</p>
</div>
<script>
const htmlCollection =
document.getElementsByTagName("a");
const array = Array.from(htmlCollection);
console.log(array);
</script>
</body>
</html>
Output
Spread Operator:
We can also convert an HTML Collection to an array by using spread opera. An iterable object can be expanded into numerous components using the spread operator(...). We may make an array that has the same element as HTMLCollection by using the spread syntax enclosed in square brackets.
Syntax:
[...htmlCollection]
Example: In this example, an HTML collection is converted to an Array on an HTML page using the spread operator.
<!DOCTYPE html>
<html>
<head>
<title>Example for HTMLCollection to Array Conversion</title>
</head>
<body>
<div>
<p>This is line 1</p>
<p>This is line 2</p>
<p>This is line 3</p>
</div>
<script>
const htmlCollection =
document.getElementsByTagName("p");
const array = [...htmlCollection];
console.log(array);
</script>
</body>
</html>
Output
Using for-loop
The most popular method for converting an HTMLCollection to an array is to use a for-loop. Here, all we have to do is loop through the HTMLCollection, pushing each piece into a separate array.
Syntax:
const array = [];
for (let i = 0; i < collection.length; i++) {
array.push(collection[i]);
}
Example: In this example, an HTMLCollection is converted to an Array in an HTML page using the for loop technique.
<!DOCTYPE html>
<html>
<head>
<title>Example for HTMLCollection to Array Conversion</title>
</head>
<body>
<div>
<p>This is line 1</p>
<p>This is line 2</p>
<p>This is line 3</p>
</div>
<script>
const collection = document.getElementsByTagName('p');
const array = [];
for (let i = 0; i < collection.length; i++) {
array.push(collection[i]);
}
console.log(array);
</script>
</body>
</html>
Output
← Prev Next →