HTMLCollection - Web APIs | MDN

Instance properties

HTMLCollection.length Read only

Returns the number of items in the collection.

Instance methods

HTMLCollection.item()

Returns the specific element at the given zero-based index into the list. Returns null if the index is out of range.

An alternative to accessing collection[i] (which instead returns undefined when i is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations.

HTMLCollection.namedItem()

Returns the specific node whose ID or, as a fallback, name matches the string specified by 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.

An alternative to accessing collection[name] (which instead returns undefined when name does not exist). This is mostly useful for non-JavaScript DOM implementations.

Usage in JavaScript

HTMLCollection also exposes its members as properties by name and index. HTML IDs may contain : and . as valid characters, which would necessitate using bracket notation for property access. Currently, an HTMLCollection object does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML does permit these.

For example, assuming there is one <form> element in the document and its id is myForm:

js

let 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"];

Specifications

Specification
DOM
# interface-htmlcollection

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.