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.
Note: This interface is called 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. For this reason it is a good idea to make a copy (eg. using Array.from
) to iterate over if adding, moving, or removing nodes.
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;
elem1 = document.forms[0];
elem2 = document.forms.item(0);
alert(elem1 === elem2);
elem1 = document.forms.myForm;
elem2 = document.forms.namedItem("myForm");
alert(elem1 === elem2);
elem1 = document.forms["named.item.with.periods"];