- Convert a NodeList or HTMLCollection to an Array with JavaScript
- What are a NodeList and HTMLCollection ?
- 1. Array.from()
- 2. Spread syntax
- 3. Array.prototype.slice.call()
- Easiest way to convert HTMLCollection into an Array!
- What is HTMLCollection and NodeList?
- Why convert them into an Array?
- Use Case
- JavaScript | Как превратить HTMLCollection в Array? (Коллекцию HTML элементов в массив)
- В чём тут проблема?
- Исходный код
- Задача
- Решение
- Способ № 2
- Html collection to list
- TL;DR
- HTMLCollection forEach loop – Convert object to array: JavaScript
- Convert to array using a spread operator
- Convert to array using Array.from()
- Convert to array using Array.prototype.slice.call()
- Convert to array using an iterator loop
Convert a NodeList or HTMLCollection to an Array with JavaScript
There are 3 ways to convert NodeList or HTMLCollection to an Array in JavaScript.
What are a NodeList and HTMLCollection ?
When selecting element on the page, with .querySelectorAll() :
const paragraphs = document.querySelectorAll('p')
it will return all paragraph elements on the page as a NodeList .
The NodeList is a collection of DOM nodes that has similar to an Array appearance and structure.
You can, however, select element via other ways like all form elements or all forms in the document via document.forms :
This property will return all form elements on the page and the result will be an HTMLCollection . The HTMLCollection returns a collection of HTML elements it also has an array-like structure.
So what’s the problem?
Both NodeList and HTMLCollection are collections and they might look like an Array and even possess some properties and methods inherent to arrays, they’re still not actual arrays.
This means if you’re willing to use Array methods like .map() , .filter() , .sort() on your NodeList s and HTMLCollection s then you’ll need to convert them into an actual Array.
1. Array.from()
Array.from() method will create a new Array instance from an array-like or iterable object. So it can be used both on NodeList and HTMLCollection .
const paragraphs = document.querySelectorAll('p') // NodeList const paragraphsArray = Array.from(paragraphs) paragraphsArray // Will output an Array const documentForms = document.forms // HTMLCollection const documentFormsArray = Array.from(documentForms) documentFormsArray // Will output an Array
This is a clear and straightforward method to create an Array , and not only from NodeList or HTMLCollection .
Browser Support: All major browsers except IE.
2. Spread syntax
Spread syntax allows an iterable such as an array expression or string to be expanded
— MDN
In the case of NodeList or HTMLCollection , the Spread syntax has to be used inside square brackets to spread iterable into a new Array .
const paragraphs = document.querySelectorAll('p') // NodeList const paragraphsArray = [. paragraphs] paragraphsArray // Will output an Array const documentForms = document.forms // HTMLCollection const documentFormsArray = [. documentForms] documentFormsArray // Will output an Array
This approach is useful when joining arrays.
Browser Support: All major browsers except IE.
3. Array.prototype.slice.call()
This is the old school method, when modern features like the ones above weren’t available.
What this piece of code does is it takes the .slice() method from Array prototype and then invokes this method by binding it to the object (in our case NodeList or HTMLCollection ) via .call() method.
return a shallow copy of a portion of an array into a new array object selected from begin to end
— MDN
But since no arguments passed it will return the full array.
const paragraphs = document.querySelectorAll('p') // NodeList const paragraphsArray = Array.prototype.slice.call(paragraphs) paragraphsArray // Will output an Array const documentForms = document.forms // HTMLCollection const documentFormsArray = Array.prototype.slice.call(documentForms) documentFormsArray // Will output an Array
Also just to shorten up a bit you can use the [].slice.call() syntax instead.
Browser Support: All major browsers.
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]; // Or use Array.from method as suggested by Traek Wells in comments. 😎 var imageHtmlCollection = document.getElementsByTagName('img'); imageHtmlCollection = Array.from(htmlCollection); // 🎉🎉
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.
JavaScript | Как превратить HTMLCollection в Array? (Коллекцию HTML элементов в массив)
Когда мы используем метод getElementsByTagName() интерфейса Document , мы получаем массиво-подобный объект интерфейса HTMLCollection .
В чём тут проблема?
Для коллекции HTML-элементов невозможно применить методы массивов, например метод map() . То есть если мы хотим пройтись по каждому элементу объекта HTMLCollection и шаблонно внести преобразования, то у нас ничего не получится т.к. в этом случае map() не будет считаться функцией.
Вот и получается, что нам сначала нужно из HTMLCollection сделать Array, а уже потом манипулировать с данными так как нам это нужно.
Исходный код
Например, мы имеем такой код:
HTMLCollection в Array JavaScript Как? мой Что? Почему? лучший Зачем? друг
Задача
Получить всё внутреннее содержимое абзацев
и представить его в виде одной строки.
Решение
1. Получаем коллекцию HTML-элементов
var vseP = document.getElementsByTagName("p")
Пробуем применить метод map() по коллекции.
var mapP = vseP.map(t => return t.innerText>)
2. Превращаем коллекцию HTML-элементов
в массив. Будем использовать свойство конструктора Array — Array.from()
var vseParray = Array.from(vseP)
3. Применяем к массиву метод map() и достаём из каждого элемента внутреннее текстовое содержимое при помощи атрибута innerText. Получается новый массив (второй)
var mapP = vseParray.map(t => return t.innerText>)
4. Теперь нам остаётся просто получить строку с нужным содержанием. Для этого мы воспользуемся методом массивов join() , где в качестве разделителя будем использовать пробел.
Способ № 2
Можно использовать Spread оператор языка JavaScript — «. . .» , чтобы получить массив.
Html collection to list
August 24, 2021 — 2 min read
To convert an HTMLCollection object to an array, we can use the from() method from the global Array object in JavaScript.
TL;DR
// Get all the references to the elements with classname 'header'. // The method return an HTMLCollection object. const headers = document.getElementsByClassName("header"); // Convert HTMLCollection object to array // using the Array.from() method const headersArr = Array.from(headers); console.log(headersArr); // [div.header, div.header]
For example, let’s say we have a two div tags with same class name called header in the HTML template like this,
div class="header">Header 1 div> div class="header">Header 2 div>
So if we were to get all the elements with the class name called header , we can use the getElementsByClassName method from the global document object and pass the class name as an argument to the method. In our case, the class name is header .
// Get all the references to the elements with classname 'header'. // The method return an HTMLCollection object. const headers = document.getElementsByClassName("header");
The above method returns the references to both the div tags as an HTMLCollection object which is an array-like object but not an array.
So to convert this HTMLCollection object to an array , we can use the Array.from() method and pass the HTMLCollection object as an argument to the method.
// Get all the references to the elements with classname 'header'. // The method return an HTMLCollection object. const headers = document.getElementsByClassName("header"); // Convert HTMLCollection object to array // using the Array.from() method const headersArr = Array.from(headers); console.log(headersArr); // [div.header, div.header]
Now if we log the output of the headersArr using the console.log() method we can see that the HTMLCollection object is now converted to an Array in JavaScirpt 🎉.
Now we can use all the native array methods in JavaScirpt like map() , forEach() , find() , filter() , etc.
See the above code live in JSBin.
HTMLCollection forEach loop – Convert object to array: JavaScript
Ever had an array-like object that you want to iterate over? These annoying collections, which look like arrays, don’t have access to useful array methods like the ‘forEach‘ loop. They include objects with a length property, such as HTMLCollection, NodeList, argument list and even strings. Today I’m going to show you how to make these objects a little bit more useful, by converting them into JavaScript arrays.
Let’s start with a simple scenario where we have 5 divs. Each div has the same class and we query for a HTMLCollection using ‘getElementsByClassName‘.
Here are 4 ways to convert the returned HTMLCollection to an array.
Convert to array using a spread operator
A spread operator will allow us to expand the values of our array-like object and push them into a new array. This works because the HTMLCollection is iterable. The code looks something like this:
const boxArray = [. document.getElementsByClassName('box')];
Convert to array using Array.from()
Array.from does what it sounds like; it converts array-like objects to actual arrays. This is my preferred method of converting to array because it is semantically very easy to read at a glance. You should note that this method isn’t actually supported by Internet Explorer, but who cares about Internet Explorer now anyway…
const boxes = Array.from(document.getElementsByClassName('box'));
Convert to array using Array.prototype.slice.call()
More widely supported, we can use the Array.prototype.slice.call() (or [].slice.call for short) methods for converting. Basically we are using the array method ‘slice‘ (which returns a copy of an array) on an array-like object with a ‘call’ method, and then saving the copy into a new array object.
var boxes = Array.prototype.slice.call(document.getElementsByClassName('box')); var boxes = [].slice.call(document.getElementsByClassName('box'));
Convert to array using an iterator loop
Last, but not least, you could solve this problem the good old fashioned way; with a simple iterator loop. From here we could loop our array-like object ‘as-is’ or push each iteration to a new array (in this case ‘boxArray’) for a future use.
const boxes = document.getElementsByClassName('box'); const boxArray = []; for (let i = 0; i < boxes.length; i++) < console.log(boxes[i]); // At this point we could also push the elements to an array boxArray.push(boxes[i]); >