Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP
by Steven M. Schafer
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...
}
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access