The Anchors Collection

Note : Both Netscape and Internet Explorer support the Anchors collection (Netscape call it an array). For properties, methods and events that are supported by <A> elements, see the <A> topic.

The Anchors collection is an ordered, indexed array, containing a reference to every <A> element in a document, that has a valid NAME and/or ID attribute. (The Links collection contains <A HREF="..." ...> elements).

Anchor Objects would normally be retrieved by their index in the Anchors collection. I.e.:

document.anchors(1).title

returns the TITLE attribute of the second anchor in the document (which may not be the second <A> element in the document).

A string value can be used however, as long as that string is a valid identifier (ID attribute value) for an element in the document.

E.g.

document.anchors('Anchor1').title

would return the TITLE attribute of the anchor whose NAME property is 'Anchor1'.

Properties

length
The length property returns the number of anchors in the collection. Note that the length count starts at 1, not 0 as the anchors collection index does. Therefore, the length property may return a value of 5, but to access the 3rd anchor, you'd need to use document.anchors(2).property

Methods

item
The item method retrieves single items, or sub-collections from the anchors collection. It accepts the following arguments:

anchors.item(index, sub-index)

If index is a number, then the method returns a reference to the anchor at that position in the anchors collections index. I.e. (using the example above)

strTag=document.anchors.item(2).title

would make strTag be the value of the TITLE attribute of the documents third anchor. As you can see, this is effectively the long-hand version of using document.anchors(2).property.

If the index property is a string value, then the item method returns a sub-collection, containing a reference to every anchor in the document that has its NAME or ID attribute set to the string contained in the index argument. To retrieve certain element objects from this sub-collection, the sub-index argument must be used.

Comments: