|
The JavaScript Tree
The document object and its bgColor
property are separated by a period. Thus,
document.bgColor refers to the background color
property of the document. That seems simple enough, but what do
you make of this?
document.mailform.address.value
It refers to the value of the address
element of a form called mailform, which is in the
document. Clear as mud? It makes a little more sense
if you think of it as a tree.
In general, JavaScript organizes all parts of the browser window
and all elements on a page (e.g., forms and images) like a tree.
First, there's a main object (the trunk), then there are objects
off the main object (branches), and finally there are methods and
properties off those objects (leaves). As you'll see in later
chapters, this is referred to technically as the document object
model, but the tree metaphor is an easier way to think about it
for now.
The main object, the trunk, is always the current browser window,
referred to as window. There are many branches off
the browser window: the page currently displayed in the window,
called document, the current location of the window,
called location, the history of all the visited
pages of the window, called history, and the value
of the status bar, status. Inside each of these
branches, you'll find more objects. For example, the
document object contains all the elements on a given
page: forms, images, and links are all reflected as objects. To
illustrate this concept, the figure shows a small "slice" of the
JavaScript tree.
As you can see, the tree begins with the browser window and
branches off from there. (This is by no means the complete
JavaScript tree, which would take up about 20 pages.) Whenever
you want to access something in the JavaScript tree, you have to
"climb" up to it. To better understand this, let's create our own
example of "climbing the tree" using a simple HTML document:
<html>
<body>
<form name="mailform">
<input type="text" name="address">
</form>
</body>
</html>
The names of the form and the text input field specified in their
HTML tags correspond to the names used by JavaScript. Here we
have a form named mailform that contains a text
input field named address. To get the text entered
by the user, you need to ask for the value of
address. That's the value of
address in form mailform in the
document in the window:
window.document.mailform.address.value
Because it is very common to access elements in the current page,
JavaScript lets you take a shortcut and start climbing the tree
at document. Thus, you can also access the text of
the address field as:
document.mailform.address.value
|