How to use for-loop In HTML
This is the most common approach to convert an HTMLCollection to an array. Here we simply iterate over the HTMLCollection and push each element into a new array.
Syntax:
const array = [];
for (let i = 0; i < collection.length; i++) {
array.push(collection[i]);
}
Example: This example uses the for loop approach to convert an HTMLCollection to an Array in an HTML document.
HTML
<!DOCTYPE html> < html > < head > < title >HTMLCollection to Array Conversion</ title > </ head > < body > < div > < p >This is para 1</ p > < p >This is para 2</ p > < p >This is para 3</ p > </ div > < script > // Return an HTMLCollection 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:
Most efficient Way to Convert an HTMLCollection to an Array
An HTMLCollection is a collection of HTML elements that looks like an array, and it is returned by various DOM methods, such as “getElementsByTagName” or “querySelectorAll”. However, this collection is not an actual array, and it does not support array-specific operations. Therefore, it may be necessary to convert the HTMLCollection to an array to perform certain array-specific operations. This article will explore all possible methods of converting an HTMLCollection to an array.
Table of Content
- Using Array. prototype.slice( )
- Using Array.from()
- Using Spread Operator
- Using for-loop