Immagini del documento HTML DOM
Esempio
Il numero di elementi <img> nel documento:
document.images.length;
Esegui il ciclo su tutti gli elementi <img> e genera l'URL (src) di ciascuno:
const myImages = document.images;
let text = "";
for (let i = 0; i < myImages.length; i++) {
text += myImages[i].src + "<br>";
}
L'URL del primo elemento <img> è:
document.images[0].src;
L'URL del primo elemento <img> è:
document.images.item(0).src;
Altri esempi di seguito.
Definizione e utilizzo
La images
proprietà restituisce una raccolta di tutti gli elementi <img> in un documento.
La images
proprietà restituisce un HTMLCollection .
La images
proprietà è di sola lettura.
Nota
La images
proprietà non restituisce elementi <input> con type="image".
Guarda anche:
Collezione HTML
Una HTMLCollection è una raccolta di nodi HTML.
È possibile accedere ai nodi in una raccolta tramite numeri di indice. L'indice inizia da 0.
La proprietà length restituisce il numero di elementi nella raccolta.
Sintassi
document.images
Proprietà
Property | Description |
length | The number of <img> elements in the collection. |
Metodi
Method | Description |
[index] | Returns the element with the specified index (starts at 0). Returns null if the index is out of range. |
item(index) | Returns the element with the specified index (starts at 0). Returns null if the index is out of range. |
namedItem(id) | Returns the element with the specified id. Returns null if the id does not exist. |
Valore di ritorno
Tipo | Descrizione |
Oggetto | Un oggetto HTMLCollection. Tutti gli elementi <img> nel documento. Gli elementi vengono ordinati come appaiono nel documento. |
Altri esempi
L'URL dell'elemento <img> con id="myImg" è:
document.images.namedItem("myImg").src;
Aggiungi un bordo nero al primo elemento <img>:
document.images[0].style.border = "10px dotted black";
Supporto browser
document.images
è una funzionalità DOM di livello 1 (1998).
È completamente supportato in tutti i browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |