English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
L'oggetto HTMLCollection rappresenta un insieme generale di elementi (simile a un oggetto array, simile a un argomento) in ordine di documento e fornisce metodi e proprietà per la selezione dalla lista.
L'HTMLCollection in HTML DOM è in tempo reale; si aggiorna automaticamente quando il documento di base viene modificato.
Metodi come getElementsByTagName() restituiscono un HTMLCollection.
La tabella seguente elenca le proprietà e i metodi dell'oggetto HTMLCollection:
Proprietà/Metodo | Descrizione |
---|---|
item() | Restituisce l'elemento all'indice specificato nell'HTMLCollection |
length | Restituisce il numero di elementi nell'HTMLCollection |
namedItem() | Restituisce l'elemento con ID o nome specificato nell'HTMLCollection |
Questo esempio restituisce un HTMLCollection:
// Restituisce l'insieme dei documenti elementi di tutti i <p> var x = document.getElementsByTagName("p");Prova a vedere‹/›
Cambia il contenuto HTML del primo elemento <p> di questo documento:
var x = document.getElementsByTagName("p"); x.item(0).innerHTML = "HELLO WORLD";Prova a vedere‹/›
Trova quante <p> ci sono nel documento:
var len = document.getElementsByTagName("p").length;Prova a vedere‹/›
Ottieni il contenuto dell'elemento <p> con ID "demo":
var x = document.getElementsByTagName("p").namedItem("demo"); document.getElementById("output").innerHTML = x.innerHTML;Prova a vedere‹/›
Puoi anche usare il metodo abbreviato, che produrrà lo stesso risultato:
var x = document.getElementsByTagName("p")["demo"]; document.getElementById("output").innerHTML = x.innerHTML;Prova a vedere‹/›