HTMLCollection

HTMLCollection is an interface representing a generic collection of elements (in document order) and offers methods and properties for traversing the list.

注記: This interface is called HTMLCollection for historical reasons (before DOM4, collections implementing this interface could only have HTML elements as their items).

HTMLCollections in the HTML DOM are live; they are automatically updated when the underlying document is changed.

DOM usage of HTMLCollections

Several DOM objects have properties that return HTMLCollection objects.

Document
anchors, document.applets, document.images, document.links, document.forms, document.scripts
HTMLDataListElement
datalist.options
HTMLFormElement
form.elements
map
map.areas
table
table.rows, table.tBodies
tableSection
tableSection.rows
row
row.cells

プロパティ

length
The number of items in the collection. Read only.

メソッド

item(index)
Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range.
namedItem(name)
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.

Usage in JavaScript

In JavaScript code that accesses HTMLCollections, in order to get an item of the given HTMLCollection, you can use the square bracket syntax instead of directly calling the item() or namedItem() methods. Numeric values in the square brackets will work the same way as item(), string values will work the same way as namedItem().

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"

ブラウザ実装状況

Different browsers behave differently when there are more than one elements matching the string used as an index (or namedItem's argument). Firefox 8 behaves as specified in DOM 2 and DOM4, returning the first matching element. WebKit browsers and Internet Explorer in this case return another HTMLCollection and Opera returns a NodeList of all matching elements.

仕様

関連情報

Document Tags and Contributors

Contributors to this page: nonki777, ethertank
最終更新者: ethertank,