![]() |
Array.from
is a JavaScript method that allows you to convert objects similar to array (like NodeList or HTMLCollection) into real arrays. This isvery useful when working with the DOM, because thequerySelectorAll
,getElementsByClassName
, etc.methods don't return actual arrays, but rather similar structures.
π️ What is it for in the DOM?
When you use DOM methods like:
const buttons = document.querySelectorAll('button');
What you get is a NodeList
, not a real array. So you can't use methods like .map()
, .filter()
, .reduce()
.
To make it a real array:
const buttonsArray = Array.from(buttons);
Now you can use all the array methods!
π§ Syntax
Array.from(arrayLike, mapFunction, thisArg)
- arrayLike: for example, a
NodeList
- mapFunction (optional): a function to transform each element
- thisArg (optional): object from use as
this
in the function
π‘ Practical examples in the DOM
1. Add a class to all elements
const divs = document.querySelectorAll('div');
Array.from(divs, div => div.classList.add('highlight'));
✅ We use Array.from
to be able to use map
directly, without forEach
.
2. Get the text of all paragraphs
const paragraphs = document.querySelectorAll('p');
const texts = Array.from(paragraphs, p => p.textContent);
console.log(texts); // ['First paragraph', 'Second paragraph', ...]
3. Disable all <input>
itemsconst inputs = document.querySelectorAll('input');
Array.from(inputs).forEach(input => {
input.disabled = true;
});
4. Create an array of DOM elements with data attributes
const items = document.querySelectorAll('[data-id]');
const dataIds = Array.from(items, item => item.dataset.id);
console.log(dataIds); // ['101', '102', '103']
5. In combination with thisArg
(advanced, rarely needed)
const state = {
prefix: 'Item: '
};
const list = document.querySelectorAll('li');
const labels = Array.from(list, function (el) {
return this.prefix + el.textContent;
}, state);
console.log(labels); // ['Item: Apple', 'Item: Banana', ...]
⚠️ Use normal functions, not arrow functions, if you want to use thisArg
.
π Why not just use [...elements]
?
The spread operator ([...document.querySelectorAll('div')]
) works for conversion, but it doesn't allow you to apply transformations directly.
Example:
// Simple conversion
const divs = [...document.querySelectorAlll('div')];
// With transformation
const ids = Array.from(document.querySelectorAll('div'), div => div.id);
π§ Conclusion
Use Array.from
when:
- You want to quickly convert a NodeList to an array
- You want to transform the elements immediately during the conversion
- You want to apply array methods (
map
,filter
, etc.) to DOM elements
It's a fundamental tool for anyone working with the DOM and wanting to write cleaner code. readable and modular.
Follow me #techelopment
Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
whatsapp: Techelopment
youtube: @techelopment