The HTMLCollection
interface represents a generic collection (array-like object similar to arguments) of elements (in document order) and offers methods and properties for selecting from the list.
HTMLCollection
for historical reasons (before the modern DOM, collections implementing this interface could only have HTML elements as their items).An HTMLCollection
in the HTML DOM is live; it is automatically updated when the underlying document is changed.
HTMLCollection.length
Read only
HTMLCollection.item()
index
into the list. Returns null
if the index
is out of range.HTMLCollection.namedItem()
name
. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name
attribute. Returns null
if no node exists by the given name.HTMLCollection
also exposes its members directly as properties by both name and index. HTML IDs may contain :
and .
as valid characters, which would necessitate using bracket notation for property access. Currently HTMLCollections does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML5 does permit these.
For example, assuming there is one <form>
element in the document and its id
is "myForm"
:
var elem1, elem2; // document.forms is an HTMLCollection elem1 = document.forms[0]; elem2 = document.forms.item(0); alert(elem1 === elem2); // shows: "true" elem1 = document.forms.myForm; elem2 = document.forms.namedItem("myForm"); alert(elem1 === elem2); // shows: "true" elem1 = document.forms["named.item.with.periods"];
Specification | Status | Comment |
---|---|---|
DOM The definition of 'HTMLCollection' in that specification. | Living Standard | |
Document Object Model (DOM) Level 2 HTML Specification The definition of 'HTMLCollection' in that specification. | Obsolete | |
Document Object Model (DOM) Level 1 Specification The definition of 'HTMLCollection' in that specification. | Obsolete | Initial definition. |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | ? | Yes | ? | ? | ? |
length |
Yes | ? | Yes | ? | ? | ? |
item |
Yes | ? | Yes | ? | ? | ? |
namedItem |
Yes | ? | Yes | ? | ? | ? |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | ? | Yes | ? | ? | ? |
length |
Yes | Yes | ? | Yes | ? | ? | ? |
item |
Yes | Yes | ? | Yes | ? | ? | ? |
namedItem |
Yes | Yes | ? | Yes | ? | ? | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection