How to use Array. prototype.slice() In HTML
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.
Syntax:
Array.prototype.slice.call(htmlCollection)
Example: This example uses the Array.prototype.slice() 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.prototype .slice.call(htmlCollection); 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