22.2. Accessing an Element by Its ID

One of the surest methods to access a document's elements is to use the getElementById() function. This function is supported by any DOM Level 1-compliant user agent, so it can be relied upon to access elements that have a properly assigned ID attribute.

The syntax of the getElementById() function is straightforward:

element = getElementById("elementID");

For example, the following code would assign a reference to the address field to the element variable:

element = getElementById("address");
...
<input type="text" size="30" id="address">

Once assigned, the element variable can be used to access the referenced field's properties and methods:

addlength = element.length;

Before using getElementById() you should test the user agent to ensure the function is available. The following if statement will generally ensure that the user agent supports the appropriate DOM level and, thus, getElementById():

if (document.all || document.getElementById) {
  ...getElementById should be available, use it...
}

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.