How to use Array.from() In HTML

The Array.from() method is available from ES6. This method takes an array-like iterable object and returns a new array with the same elements. In our case the array-like iterable object is HTMLCollection. We simply pass it to this method and accept an array from it.

Syntax:

Array.from(htmlCollection)

Example: This example uses the Array.from() method 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 htmlCollection =
            document.getElementsByTagName("p");
        const array = Array.from(htmlCollection);
        console.log(array);
    </script>
</body>
 
</html>


Output:

HTMLCollection to Array – Method 2

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

Similar Reads

Using Array. prototype.slice():

In this method, we bind the call() method with Array.prototype.slice(). This will invoke Array.prototype.slice() on HTMLCollection. This method converts the HTMLCollection to the array by creating a shallow copy of it. Below is the syntax we’ll use....

Using Array.from():

...

Using Spread Operator:

The Array.from() method is available from ES6. This method takes an array-like iterable object and returns a new array with the same elements. In our case the array-like iterable object is HTMLCollection. We simply pass it to this method and accept an array from it....

Using for-loop:

...

Contact Us