🧠 Array.from in JavaScript: la guida pratica per il DOM

 


Array.from è un metodo di JavaScript che ti permette di convertire oggetti simili ad array (come NodeList o HTMLCollection) in veri array. Questo è molto utile quando lavori con il DOM, perché i metodi querySelectorAllgetElementsByClassName, ecc. non restituiscono veri array, ma strutture simili.

🔗 Ti piace Techelopment? Dai un'occhiata al sito per tutti i dettagli!

🏗️ A cosa serve nel DOM?

Quando usi metodi del DOM come:

const buttons = document.querySelectorAll('button');

Quello che ottieni è una NodeList, non un vero array. Quindi non puoi usare metodi come .map(), .filter(), .reduce().

Per farlo diventare un array vero:

const buttonsArray = Array.from(buttons);

Ora puoi usare tutti i metodi degli array!


🔧 Sintassi

Array.from(arrayLike, mapFunction, thisArg)
  • arrayLike: ad esempio una NodeList
  • mapFunction (opzionale): una funzione per trasformare ogni elemento
  • thisArg (opzionale): oggetto da usare come this nella funzione

💡 Esempi pratici nel DOM

1. Aggiungere una classe a tutti gli elementi

const divs = document.querySelectorAll('div');

Array.from(divs, div => div.classList.add('highlight'));

✅ Usiamo Array.from per poter usare map direttamente, senza forEach.


2. Ottienere il testo di tutti i paragrafi

const paragraphs = document.querySelectorAll('p');

const texts = Array.from(paragraphs, p => p.textContent);
console.log(texts); // ['First paragraph', 'Second paragraph', ...]

3. Disabilitare tutti gli elementi <input>

const inputs = document.querySelectorAll('input');

Array.from(inputs).forEach(input => {
  input.disabled = true;
});

4. Creare un array di elementi DOM con 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 combinazione con thisArg (avanzato, raramente necessario)

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', ...]

⚠️ Usa funzioni normali, non arrow function, se vuoi usare thisArg.


🆚 Perché non usare solo [...elements]?

Lo spread operator ([...document.querySelectorAll('div')]) funziona per convertire, ma non ti permette di applicare trasformazioni direttamente.

Esempio:

// Semplice conversione
const divs = [...document.querySelectorAll('div')];

// Con trasformazione
const ids = Array.from(document.querySelectorAll('div'), div => div.id);

🧠 Conclusione

Usa Array.from quando:

  • Vuoi convertire rapidamente un NodeList in array
  • Vuoi trasformare gli elementi subito durante la conversione
  • Vuoi applicare metodi array (map, filter, ecc.) a elementi DOM

È uno strumento fondamentale per chi lavora con il DOM e vuole scrivere codice più pulito, leggibile e modulare.



Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment