An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
Easiest way to convert HTMLCollection into an Array!
There are two ways in which you can convert an HTMLCollection or a NodeList into an array.
If you don't know what an HTMLCollection and a NodeList is, or why you would need to convert them into a normal Array, hold tight, I'll explain them soon enough!
// First, pre-ES6 way.var htmlCollection = document.getElementsByClassName('btn');htmlCollection = Array.prototype.slice.call(elements);// Or you could do the same thing using ES6 syntax.var nodeList = document.querySelectorAll('.btn');nodeList = [...nodeList];//
What is HTMLCollection and NodeList?
When you use methods like getElementsByClassName
or querySelectorAll
they return an HTMLCollection or NodeList respectively instead of an Array.
HTMLCollection contains HTML elements whereas NodeList goes a few steps further, it not only returns a list of HTML elements but can also return Nodes like TextNode and has additional methods list NodeList.forEach.
For a more detailed discussion on the topic, you may read this stackoverflow post called: The difference between HTMLCollection, NodeList and Array.
Why convert them into an Array?
The only reason to convert an HTMLCollection and NodeList to an Array is, if you want to use higher order functions like forEach, map, filter and reduce.
There are a lot of use cases, for instance, let's say you have elements that contain a data-src
property along with lazy-load
class. If you want to access the data-src
and filter out all the elements that don't have data-src
or are empty, you may do the following.
Use Case
var lazyLoadables = [...document.querySelectorAll('.lazy-load')] .filter((element) => element.getAttribute('data-src').trim());lazyLoadImages(lazyLoadables);
By doing this, you made sure only to pass the elements that have a source that needs to be loaded when it is required.
Original Link: https://dev.to/hasnaindev/easiest-way-to-convert-htmlcollection-into-an-array-bkl
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To