Document.getElementById() (Method)

An accessor method for retrieving objects from within the DOM hierarchy specifically according to their ID value.


DOM level - 1
JavaScript - 1.5
JScript - 5.0
Internet Explorer - 5.0
Netscape - 6.0
Opera - 5.0
Property/method value type:Element object
JavaScript syntax:-myDocument.getElementById(anID)
Argument list:anIDThe ID value of an object to locate in a string

Sometimes, it can be inconvenient to walk the document hierarchy to locate an object by its ID. One alternative is to search the all[] collection on the MSIE browser but this is a linear search that takes place serially through the document object collection from beginning to end. It can take quite a while to locate the object.

There may also be some conflict in locating objects. The ID and NAME attributes are different and yet often the two namespaces are combined and searched together.

This method is a faster way of locating an object specifically by its ID value and ignoring its NAME value. It searches the only unmerged namespace for the ID value.

The DOM level 1 specification notes that the behavior is undefined if more than one item shares the same ID. Running a short test on MSIE on the Macintosh platform yields the first occurring element with a matching ID value. It is likely that this is the generic behavior for versions of MSIE across all other platforms too. For now at least Netscape 6.0 seems to do the same thing.

As there is undefined behavior in the specification, you may find that some browsers return a different object. Indeed, because this is undefined, the behavior may change from one browser version to the next.