Previous Topic Tutorial Table of Contents Next Topic
JavaScript banner

 
The Document Object Model (DOM)


Prelude |  The DOM  |  Referencing Objects
The Three Facets of Objects: 
Properties
Methods
Event Handlers

Prelude

To write web scripts in JavaScript, there are two things you must be familiar with:

  1. The core language of JavaScript
  2. The Document Object Model 
The core language is composed of the syntax of the language, control structures (if statements, for and while loops), the standard variable types (var and arrays) and the global functions that are available (such as parseInt()). The core language has been standardized as ECMAScript. This standardization was possible, in part, because Microsoft's JScript and Netscape's JavaScript are essentially identical in the core language. This uniformity is not the case for the DOM implemented by the Netscape and Microsoft browsers, at least as of NN4 and IE4. There may be a convergance of DOM implementation in the future, which the W3C will codify.

The DOM

The DOM is the architecture of in-built objects that the core language can manipulate. As your web page loads into a browser, items in your page that are objects in the DOM get loaded into the browser's object model as scriptable objects.

A scriptable object is one that can be accessed by means of your script. For example, suppose I define a text entry box in a form. As the page loads, the browser creates a scriptable textbox object and a form object in its memory. If I create two text entry boxes in my html, then the browser creates two textbox objects in its memory. JavaScript code on your page can now access those object.

Which aspects of your html code become scriptable objects in the memory of the browser is dictated by the DOM. In NN4, for example, text inside <p> </p> tags is not a scriptable object, because there no "p" or "paragraph" object defined in the current Netscape DOM. (This will change.) Nor is there a "table" object, so tables are not scriptable objects. Images (in NN3+), links, forms and text entry boxes are some of the objects that are defined in the DOM. It is likely that almost all tags will become part of the DOM in future browsers, in which the power of JavaScript will grow accordingly.

The DOM defines a hierarchical relationship between (almost) all of the objects that are defined in the DOM architecture, which is shown in this figure.  Notice that at the top of the hierarchy is the window object.  The window is the container for everything, including the toolbars (the "chrome", such as the menu and navigation buttons) and the document.

The document object lies one step below the window object; it has three siblings (history, toolbar, and location) and is the container for (almost) all of the rest of the objects, such as forms, images, applets and links.

In the DOM defined in NN4, there are 4 other scriptable DOM objects that are not part of the window object hierarchy:  the navigator object, the plugin object, the mimeType object and the screen object.

As I will only be using the navigator object of these extra objects in this tutorial, I won't discuss these here, except to say that the navigator object in IE4 (and future releases of NN?) is part of the window hierarchy. In the IE4 model, it is contained by "Window" at the same level as the document object. This does not create a cross-platform scripting problem, however, because the window reference is optional when referring to objects in your script (see below).  Thus, when referring to the navigator object, simply start the reference with navigator, instead of window.navigator, and your script will work in both browsers.

Referencing Objects

In your scripts, you will frequently be referencing objects (remember: JavaScript is an object-oriented language). The DOM hierarchy provides a road map of how to refer to any particular object via the dot syntax.

This is how you reference the document object:
window.document
or
document

Since there is only one window object, we can leave off the "window" reference and the browser still knows which document we are talking about (Note: this changes when there are frames).

Now, suppose you have the following html code:

<body>

<form name="boxes">
Enter first name: <input type="text" name="fName"> <br>
Enter last name: <input type="text" name="lName">
</form>

</body>

How would you reference the first text entry box? One way is:
document.boxes.fName

Look back to the DOM hierarchy and you will see that to get from the top window to a text object you must follow this path:
window --> document --> form --> text, or using dot syntax:
window.document.form.text. (Or just document.form.text.) However, as there can be more than one form in a document and more than one text field in a form, we cannot simply use "form" and "text" to cite them.

Instead, we should name the form and text boxes and cite them by their names, which leads to (leaving off the optional "window" reference):
document.boxes.fName
to reference the first text entry box.

There is another way, however, which you should be aware of, so that you can read other people's scripts and because this other way is a little easier for some objects. For cases where an object type can be present multiple times within a parent object (such as multiple text boxes in a form), those objects can be referenced by their location in the DOM element array that is automatically created in its parent object by your browser. This is easier to demonstrate than to describe, so here's what I mean:

To reference the first text box in the code above this way, you would write:
document.forms[0].elements[0]

This can be read as:  the first (scriptable) element (such as a checkbox, a text box or a button) in the first form in the document. An array is like a small two-column table of entries. The "[0]" notation is array notation for the first element of the array, because arrays start with the zeroth element.  See the section of this tutorial on arrays for more information.

To reference, the second text box, you would write:
document.forms[0].elements[1]

The array referencing of objects can be used whether or not the object has been given an explicit name.  Also notice that the array names are plural, not singular. It is generally advised that you give names to your html tags (using the "name" attribute) that you will be referencing in your scripts. However, using the array notation for forms is somewhat common.

As a last test of this concept, how would you reference the second check box in the following html code:

<body>

<form name="boxes">
Enter first name: <input type="text" name="fName"><br>
Enter last name: <input type="text" name="lName">
</form>
<br>
<form>
Are you a student?
<input type="checkbox" name="fred">Yes
<input type="checkbox" name="barney">No
</form>

</body>

Answer:
document.forms[1].barney
(Or document.forms[1].elements[1])

The Three Facets of Objects

Objects in the DOM have three important facets you must know about in order to write JavaScript code:  properties, methods and event handlers.

Properties

Properties are data elements of objects.  For example, one property of a text object is its name. The value of the name property is what you assign it to be in your HTML code or it is blank (null) if you did not give it a name.

DOM objects vary in what properties they possess.  For example, here is a comparison of some of the properties of the document object and the text object: 

Document Text
alinkcolor

bgcolor

forms[i]

images[i]

links[i]

title

URL

defaultValue

form

name

type

value

There are three important things to know about properties: 1) whether they are gettable, 2) what value they return when they are gettable, and 3) whether they are settable. Properties that are gettable only are also called read-only.

To get a complete listing of the properties of objects and how these properties behave you'll need a book like Danny Goodman's JavaScript Bible or you can peruse Netscape developer's online JavaScript documentation.

As an introduction, we'll sample one property of each object from the table above. Th bgcolor (background color) property of the document object is both gettable and settable and returns a hexadecimal triplet string corresponding to the current color.

To get the current value, you would write:

var c = document.bgcolor

the variable c will be a string such as "#ffcc53".  My fade-in script demonstrates the use of the bgcolor property.

To set the bgcolor property, you would write:

var c = "#212121"
document.bgcolor = c 

or just:
document.bgcolor = "#212121"


The defaultValue property of a text object corresponds to the text that is displayed inside the text box.  It is gettable--it returns the string set in the value ttribute--but it is NOT settable (in your JavaScript script, I mean; it is, of course, settable in the html <input> tag). This means that you can write:

tt>var dv = document.forms[0].moe.defaultValue

and dv will be set to the default value you specified in your code:

<input type="text" name="moe" value="shamrock">

which is "shamrock" in this case.

However, the code

var dv = "4 leaf clover"
document.forms[0].moe.defaultValue = dv

will do nothing, because you cannot change the defaultValue once the html code has been written and the page has loaded.  Don't despair, though, because you can change the current value of the textbox by setting the value of the "value" property:

document.forms[0].moe.value = dv 

Methods

Methods are built-in actions or functions that an object can perform. As with properties, what built-in methods an object can perform differs for every object.  Again, let's visit the document and text objects and look at some of their methods: 

Document Text
clear()

close()

open()

write()

blur()

focus()

select()

First, note that methods have a trailing set of parentheses after them. That is standard notation, but realize that some methods take arguments, or values, inside the parentheses, while others do not.  We will look at both kinds. 

var text = "This is a new page"
document.open()
document.write(text)
document.close()

These three document methods are typically used in conjunction to write new content to a page. The open() function opens a layout stream for writing, write() writes to it and close() closes the writing stream.   [Note: document method open() does not open a new window -- that is the job of the window method called open().] 

The document write() method takes a string argument and writes that string to t page. In the above example, we gave it the variable "text", which contains a string, bu could have also given the write() method the string directly, like so:

document.write("This is a new page")


The text object method focus() is used to place the cursor into a specific text box. The opposite of focus() is blur().

See this script for an example of how the text object focus() method can be useful for showing the user what box needs to be filled in.

Event Handlers

JavaScript is an object-oriented event-driven programming language. This means that JavaScript code responds to user-initiated events by creating and manipulating objects (and their data values).

Most objects in the DOM have specific events to which they can respond. For each of these events, there is a corresponding event handler which catches the event and points the script to what it should do in response. To respond to an event you need to register an event handler in your HTML code.

For example, one event that can occur is the famous "mouse-over", when your mouse cursor enters the territory of some screen object. The event handler for that event is called onMouseOver=. The trailing equals sign is conventional notation when referring to the handler generically.

Here's how the onMouseOver= event handler is registered in a link object:

<a href="somefile.html" onMouseOver="someFunction(); return true">*text or image \ here*</a>

When a mouse-over event occurs for this particular link object, the JavaScript function "someFunction( )" is called.  This function would be one that you as the script-writer defined elsewhere in the page. This event handler is peculiar in that it requires a "return true" statement at the end in order to complete successfully (onSubmit= and onMouseOut= require this as well).

As with properties and methods, each object has a different set of event handlers that are available to it. Some objects, such as the document object, have no event handlers available. See the event handler table for a complete listing of handlers, what objects they can be registered for and in which html tags they go.


Previous Topic Tutorial Table of Contents Next Topic