HTMLCollection

[Exposed=Window]
interface HTMLCollection {
    readonly attribute unsigned long length;
    getter Element? item(unsigned long index);
    getter Element? namedItem(DOMString name);
};

An HTMLCollection object is a collection of elements.

Elements is the better solution for representing a collection of elements. HTMLCollection is an historical artifact we cannot rid the web of.

collection.length
Returns the number of elements in the collection.

element = collection.item(index)
element = collection[index]

Returns the element with index index from the collection. The elements are sorted in tree order.

element = collection.namedItem(name)
element = collection[name]

Returns the first element with ID or name name from the collection.


The object’s supported property indices are the numbers in the range zero to one less than the number of nodes represented by the collection. If there are no such elements, then there are no supported property indices.

The length attribute must return the number of nodes represented by the collection.

The item(index) method must return the indexth element in the collection. If there is no indexth element in the collection, then the method must return null.

The supported property names, all unenumerable, are the values from the list returned by these steps:

  1. Let result be an empty list.
  2. For each element represented by the collection, in tree order, run these substeps:
    1. If element has an ID which is neither the empty string nor is in result, append element‘s ID to result.
    2. If element is in the HTML namespace and has a name attribute whose value is neither the empty string nor is in result, append element‘s name attribute value to result.
  3. Return result.

The namedItem(key) method must run these steps:

  1. If key is the empty string, return null.
  2. Return the first element in the collection for which at least one of the following is true:
    • it has an ID which is key.
    • it has a name attribute whose value is key;

    or null if there is no such element.

https://www.w3.org/TR/dom/#old-style-collections:-nodelist-and-htmlcollection

Leave a Reply