Manuale di riferimento DOM HTMLCollection

Oggetto HTMLCollection

L'oggetto HTMLCollection è una lista simile a un array di elementi HTML.

Metodi come getElementsByTagName() restituiscono un'HTMLCollection.

Proprietà e Metodi

Puoi utilizzare le seguenti proprietà e metodi sull'oggetto HTMLCollection:

Proprietà / Metodi Descrizione
item() Restituisce l'elemento all'indice specificato dell'HTMLCollection.
length Restituisce il numero di elementi dell'HTMLCollection.
namedItem() Restituisce l'elemento con ID o nome specificato dell'HTMLCollection.

Esempio

Esempio

Ottieni l'HTMLCollection:

var x = document.getElementsByTagName("P");
// Restituisce l'insieme di tutti gli elementi <P> del documento

Prova tu stesso

Esempio

Outputta la quantità di elementi <p> nel documento:

var x = document.getElementsByTagName("P");
document.write(x.length);

Prova tu stesso

Esempio

Ciclo attraverso ogni elemento dell'HTMLCollection:

x = document.getElementsByTagName("*");
l = x.length;
for (i = 0; i < l; i++) {
  document.write(x[i].tagName + "<br>");
}

Prova tu stesso