XML DOM HTMLCollection Object

HTMLCollection object

HTMLCollection is an interface that represents a collection of HTML elements, providing methods and properties that can be traversed in the list.

The HTMLCollection in HTML DOM is 'live'; if the basic document changes, those changes will be immediately displayed through all HTMLCollection objects.

Each item (and its specified properties) below returns an HTMLCollection:

  • Document (images, applets, links, forms, anchors)
  • form (elements)
  • map (areas)
  • select (options)
  • table (rows, tBodies)
  • tableSection (rows)
  • row (cells)

Many properties of HTMLDocument interface are HTMLCollection objects, which provide a convenient way to access document elements such as forms, images, and links.form.elements and select.options are all HTMLCollection objects. HTMLCollection also provides iteration Table rows as well as TableRow a convenient method for accessing various cells.

As mentioned above, HTMLCollection object is a collection of HTML elements with methods, which can be used to obtain elements by their position in the document or by their id attribute, name attribute. In JavaScript, the behavior of HTMLCollection object is like a read-only array, and it can use JavaScript brackets to index an HTMLCollection object by number or name without calling item() methodand namedItem() method.

HTMLCollection object is read-only and cannot have new elements added to it, even if the JavaScript array syntax is used.

HTMLCollection object and NodeList objectVery similar, but the former may be accessible both by name index and by numeric index.

Properties of HTMLCollection object

Property Description
cssRules Read-only property, returns an integer indicating the length of the list (i.e., the number of elements in the collection).

The methods of HTMLCollection object

Method Description
item() Returns the element (node) at the specified position in the collection.
namedItem() Returns the element (node) in the collection that has the specified value for the name attribute or id attribute.

Example

var c = document.forms;		//This is an HTMLCollection object of form elements
var firstform = c[0];		//Can be used as a numeric array
var lastform = c[c.length-1];	//The length property returns the number of elements
var address = c["address"];		//Can be used as an associative array
var address = c.address;		//JavaScript allows such notation

Related pages

XML DOM reference manual:HTMLDocument object

XML DOM reference manual:NodeList object

Reference manual:HTML DOM reference manual