Section 25.144. HTMLCollection: array of HTML elements accessible by position or name


25.144. HTMLCollection: array of HTML elements accessible by position or name

DOM Level 2 HTML: Object HTMLCollection

25.144.1. Properties


readonly unsigned long length

The number of elements in the collection.

25.144.2. Methods


item( )

Returns the element at the specified position in the collection. You can also simply specify the position within array brackets instead of calling this method explicitly.


namedItem( )

Returns the element from the collection that has the specified value for its id or name attribute, or null if there is no such element. You can also place the element name within array brackets instead of calling this method explicitly.

25.144.3. Description

An HTMLCollection is a collection of HTML elements with methods that allow you to retrieve an element by its position in the collection or by its id or name attribute. In JavaScript, HTMLCollection objects behave like read-only arrays, and you can use JavaScript square-bracket notation to index an HTMLCollection by number or by name instead of calling the item( ) and namedItem( ) methods.

A number of the properties of the HTMLDocument object are HTMLCollection objects and provide convenient access to document elements such as forms, images, and links. The Form.elements property and Select.options property are HTMLCollection objects. The HTMLCollection object also provides a convenient way to traverse the rows of a Table and the cells of a TableRow.

HTMLCollection objects are read-only: you cannot assign new elements to them, even when using JavaScript array notation. They are "live," meaning that if the underlying document changes, those changes are immediately visible through all HTMLCollection objects.

HTMLCollection objects are similar to NodeList objects but may be indexed by name as well as by number.

25.144.4. Example

 var c = document.forms;       // This is an HTMLCollection of form elements var firstform = c[0];         // It can be used like a numeric array var lastform = c[c.length-1]; // The length property gives the number of elements var address = c["address"];   // It can be used like an associative array var address = c.address;      // JavaScript allows this notation, too 

25.144.5. See Also

HTMLDocument, NodeList




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net