2.4 The Legacy DOM
The original client-side JavaScript DOM defines provides access to
document content through properties of the Document object. Several
read-only properties, such as title,
URL, and lastModified provide
information about the document as a whole. See the reference section
for further details on these and all Document properties and methods.
Other properties are arrays that refer to specific types of document
content:
- forms[ ]
-
An array of Form objects representing the forms in a document.
- images[ ]
-
An array of Image objects representing the images that appear in a
document.
- applets[ ]
-
An array of objects that represent the Java applets embedded in a
document. JavaScript can actually be used to script Java and control
these applets, but doing so is beyond the scope of this pocket
reference.
- links[ ]
-
An array of Link objects representing the hyperlinks in the document.
- anchors[ ]
-
An array of Anchor objects representing the anchors (named positions
created with the name attribute of the HTML
<a> tag) in the document.
These arrays contain objects in the order they appear in the
document. So the first form in a document is
document.forms[0], and the third image is
document.images[2]. Another way to refer to
document forms, images, and applets is to give them names with the
HTML name attribute:
<form name="address">...</form>
When an form, image, or applet is given a name in this way, you can
use that name to look it up in the array, or to look it up directly
as a property of the document itself:
document.forms["address"] // A named form
document.address // The same thing
The Form object is particularly interesting. It has an
elements[ ] array that contains objects
representing the elements of the form, in the order they appear in
the form. See Input, Select, and Textarea in the reference section
for details on these form elements.
The elements[ ] array of a Form works much like
the forms[ ] array of a Document: it holds form
elements in the order they appear in the form, but it also allows
them to be referred to by name. Consider this HTML excerpt:
<form name='address'><input name='street'></form>
You can refer to the input element of the form in several ways:
document.forms[0].elements[0]
document.address.elements['street']
document.address.street
The legacy DOM does not provide any way to refer to document content
other than forms, form elements, images, applets, links, and anchors.
There is no array that provides a list of all
<h1> tags, for example, nor is there any way
for a script to obtain the actual text of a document. This is a
shortcoming that is addressed by the W3C and IE 4 DOMs, as
we'll see later. Although it is limited, the legacy
DOM does allow scripts to dynamically alter some document content, as
we'll see in the following subsections.
2.4.1 Dynamically generated documents
In addition to the properties already described, the Document object
defines several important methods for dynamically generating document
content. Use the write( ) method to output text
into the document at the location of the
<script> that contains the method calls. For
example:
document.write("<p>Today is: " + new Date());
document.write("<p>Document updated: " +
document.lastModified);
Note that text output in this way may contain arbitrary HTML tags;
the browser parses and displays any such text after executing the
script that output it.
The write( ) method can be used from a
<script> tag only while a document is still
loading. If you try to use it within an event handler that is
triggered after the document has loaded, it erases the document and
the event handler it contains. It is legal, however, to use an event
handler in one window or frame to trigger a document.write(
) call into another window. When you do this, however, you
must write the complete contents of the new document, and remember to
call the document.close( ) method when you are
done:
var clock = open("", "", "width=400,height=30");
var d = clock.document; // Save typing below
setInterval("d.write(new Date());d.close();",
1000);
2.4.2 Dynamic forms
As we've seen, the elements[ ]
array of a Form object contains objects that represent the input
elements of the form. Many of these objects have properties that you
can use to query or set the value displayed in the form element. This
provides another way to dynamically change document content. For
example, the following code sets the value
property of a Text object to display the current local time.
<form><input size=10></form> // An HTML form
<script> /* Display a clock in the form */
// The Text element we're working with.
var e = document.forms[0].elements[0];
// Code to display the time in that element
var s="e.value=(new Date()).toLocaleTimeString();"
setInterval(s, 1000); // Run it every second
</script>
2.4.3 Form validation
The <form> tag supports an
onsubmit event handler, which is triggered when
the user tries to submit a form. You can use this event handler to
perform validation: checking that all required
fields have been filled in, for example. If the
onsubmit handler returns false,
the form is not submitted. For example:
<form name="address" onsubmit="checkAddress()">
<!-- form elements go here -->
</form>
<script>
// A simple form validation function
function checkAddress() {
var f = document.address; // The form to check
// Loop through all elements
for(var i = 0; i < f.elements.length; i++) {
// Ignore all but text input elements
if (f.elements[i].type != "text") continue;
// Get the user's entry
var text = f.elements[i].value;
// If it is not filled in, alert the user
if (text == null || text.length == 0) {
alert("Please fill in all form fields.");
return false;
}
}
}
</script>
2.4.4 Image rollovers
The legacy DOM allows you to accomplish one common special effect:
dynamically replacing one image on the page with another. This is
often done for image rollovers, in which an image changes when the
mouse moves over it. The images[ ] array of the
Document object contains Image objects that represent the
document's images. Each Image object has a
src property that specifies the URL of the image
to be displayed. To change the image that is displayed, simply set
this property to a new URL:
document.images[0].src = "newbanner.gif";
To use this technique for an image rollover, you must use it in
conjunction with the onmouseover and
onmouseout event handlers that are triggered when
the mouse moves on to and off of the image. Here is some basic HTML
code with JavaScript event handlers to accomplish a rollover:
<img name="button" src="b1.gif"
onmouseover="document.button.src='b2.gif';"
onmouseout="document.button.src='b1.gif';">
When an image is going to be dynamically displayed, it is helpful to
preload it into the browser cache so that there is no network delay
before it appears. You can do this with a dynamically created
off-screen Image object:
var i = new Image(); // Create Image object
i.src="b2.gif"; // Load, but don't display image
2.4.5 Working with cookies
The cookie property of the Document object is a
peculiar one that allows you to set and query the cookies associated
with your document. To associate a transient cookie with the
document, simply set the cookie property to a
string of the form:
name=value
This creates a cookie with the specified
name and value
for this document. If you want to create a cookie that is stored even
when the user quits the browser, add an expiration date using a
string of the form:
name=value; expires=date
The expiration date should be in the form
returned by Date.toGMTString( ). If you want the
cookie to be accessible to other documents from your web site, you
can specify a path prefix:
name=value; expires=date; path=prefix
A single document may have more than one cookie associated with it.
To query a document's cookies, simply read the value
of the cookie property. This string contains
name=value strings separated from each
other by a semicolon and a space. When reading cookies,
you'll never see a
"path=" or
"expires=" clause;
you'll just get the cookie name and value.
Here's a function that retrieves the value of a
single named cookie from the cookie property. It
assumes that cookie values never contain semicolons.
function getCookie(name) {
// Split cookies into an array
var cookies = document.cookie.split('; ');
for(var i = 0; i < cookies.length; i++) {
var c = cookies[i]; // One cookie
var pos = c.indexOf('='); // Find = sign
var n = c.substring(0,pos); // Get name
if (n == name) // If it matches
return c.substring(pos+1); // Return value
}
return null; // Can't find the named cookie
}
|