Accessing Page Elements

Although recent browsers support the W3C DOM as a means of accessing elements within the current HTML page (see the section "DOM Methods" later in this chapter for more information), there are easier ways to work with data on a page. Two of them are covered in this section.

Accessing Form Elements

JavaScript’s document object grants access to all elements on the current page. document is a representation of the DOM that is accessible to JavaScript. To make the access as convenient as possible, there are several subproperties that allow direct access to special page elements. Here are some examples, listed alphabetically:

document.embeds

An array containing all embedded media (via <embed>) on the current page

document.forms

An array containing all <form> elements on the page

document.frames

An array containing all frames on the current page

document.images

An array containing all images on the current page

document.links

An array containing all hyperlinks on the current page

The most commonly used property is document.forms, which lets you access all <form> elements on the current page, such as text boxes and buttons. Admittedly, there is usually only a single form on a page. However, the document.forms[0] property (the forms property is actually an array) grants access to all elements within the first (and usually only) form. For example, imagine the following form:

<form>
  <input type="text" name="TextBox1" />
</form>

The expression document.forms[0].elements["TextBox1"] ...

Get Programming Atlas 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.