Chapter 14. The Document Object
Every Window object has a document property. This property refers to a Document
the HTML document displayed in the window. The Document
ct in client-side JavaScript. We've
already seen several examples in this book that use the
write( ) method of the
Document object to insert dynamic content into a document while it is being parsed. In
d, and so on.
it is the Doc ess to the content of
otherwise static documents. In addition to the properties that provide information about a
h t all the HTML forms in the document. And the
images[] and applets[] arrays contain objects that represent the images and applets in
pen up a world of possibilities
hapter is devoted to
documenting them.
uch as IE 4 and later and
Netscape 6 and later, implement a full document object model, or DOM, that gives
d
object that represents
object is probably the most commonly used obje
addition to the frequently used write( ) method, the Document object defines properties
that provide information about the document as a whole: its URL, its last-modified date,
the URL of the document that linked to it, the colors in which it is displaye
Client-side JavaScript exists to turn static HTML documents
ument object that gives JavaScript interactive acc
into interactive programs --
document as a whole, the Document object has a number of very important properties
that provide information about document content. The
forms[] array, for instance,
contains Form objects t at represen
the document. These arrays and the objects they contain o
for client-side JavaScript programs, and the bulk of this c
This chapter covers the core features of the Document object that are implemented by
virtually every JavaScript-enabled browser. Newer browsers, s
JavaScript complete access to and control over all document content. These advance
DOM features are covered in Chapter 17.
14.1 Document Overview
To illustrate the scope and importance of the Document object, this chapter begins with a
quick summary of the methods and properties of the object. The following sections also
explain other important material that is important to understand before reading the rest of
the chapter.
14.1.1 Document Methods
The Document object defines four key methods. One is the write( ) method, which
we've already seen several times, and the other three are related:
close( )
Close or end a document that was begun with open( ).
open( )
Begin a new document, erasing any existing document content.
write( )
Append text to the currently open document.
Output text into the currently open docu d appe ne character.
4.1.2 Document Properties
, ,
These properties describe the colors of hyperlinks. linkColor is the normal color
anchors[]
ent the Java applets in the document.
bgColor, fgColor
The background and foreground (i.e., text) colors of the document. These
properties correspond to the bgcolor and text attributes of the <body> tag.
cookie
writeln( )
ment, an nd a newli
1
The Document object defines the following properties:
alinkColor linkColor vlinkColor
of an unvisited link. vlinkColor is the normal color of a visited link.
alinkColor is the color of a link while it is activated (i.e., while the user is
clicking on it). These properties correspond to the alink , link, and vlink
attributes of the <body> tag.
An array of Anchor objects that represent the anchors in the document.
applets[]
An array of Applet objects that repres
A special property that allows JavaScript programs to read and write HTTP
cookies. See Chapter 16 for details.
domain
etA property that allows mutually trusted web servers within the same Intern
domain to collaboratively relax certain security restrictions on interactions
n their web pages. See betwee Chapter 21.
forms[]
An array of Form objects that represent the <form> elements in the document.
images[]
An array of Image objects that represent the <img> elements in the document.
lastModified
location
A deprecated synonym for the URL property.
that brought the browser to the
curre
title
The text between the <title> and </title> tags for this document.
A string that contains the modification date of the document.
links[]
An array of Link objects that represent the hypertext links in the document.
referrer
The URL of the document containing the link
nt document, if any.
URL
A string specifying the URL from which the document was loaded. The value of
this property is the same as the location.href property of the Window object,
except when a server redirect has occurred.
14.1.3 The Document Object and Standards
The Document object and the set of elements (such as forms, images, and links) that it
exposes to JavaScript programs form a document object model. Historically, different
browser vendors have implemented different DOMs, which has made it difficult for
JavaScript programmers to portably use the advanced features of the vendor-specific
DOMs. Fortunately, the World Wide Web Consortium (or W3C; see
)
dhas standardized a DOM and issued two versions of this standard, known as Level 1 an
Level 2. Recent browsers, such as Netscape 6 and later and IE 5 and later, implement
some or most of these standards. See Chapter 17 for all the details.
The DOM described in this chapter predates the W3C standards. By virtue of its nearly
e
evel 0 DOM. You can use the techniques described in this chapter in any JavaScript-
enabled web browser, with the exception of very old ones such as Netscape 2.
ect methods and properties listed previously have been
formalized as part of the Level 1 DOM, so they are guaranteed to remain supported by
O standard is that it is a document
object model for both XML and HTML documents. In this standard, the Document object
provides generic functionality of use for both types of documents. HTML-specific
functionality is provided by the HTMLDocument subclass. All the Document properties
and methods described in this chapter are HTML-specific, and you can find more details
about them under the "Document" entry in the client-side reference section of this book.
You'll also find related information in the DOM reference section, under "Document" and
"HTMLDocument."
14.1.4 Naming Document Objects
Before we begin our discussion of the Document object and the various objects it
exposes, there is one general principle that you'll find it helpful to keep in mind. As you'll
see, every
<form> element in an HTML document creates a numbered element in the
forms[] array of the Document object. Similarly, every <img> element creates an
element in the images[] array. The same applies for <a> and <applet> tags, which
define elements in the links[] and applets[] arrays.
In addition to these arrays, however, a Form, Image, or Applet object may be referred to
by name if its corresponding HTML tag is given a
name attribute. When this attribute is
universal implementation, however, it is a de facto standard and is often referred to as th
L
Furthermore, the Document obj
future browsers.
ne important thing to understand about the W3C DOM
present, its value is used to expose the corresponding object as a property of the
Document object. So, for example, suppose an HTML document contains the following
form:
<form name="f1">
<input type="button" value="Push Me">
</form>
Assuming that the <form> is the first one in the document, your JavaScript code can refer
to the resulting Form object with either of the following two expressions:
document.forms[0] // Refer to the form by position within the document
document.f1 // Refer to the form by name
In fact, setting the name attribute of a <form> also makes the Form object accessible as a
named property of the forms[] array, so you could also refer to the form with either of
these two expressions:
document.forms.f1 // Use property syntax
document.forms["f1"] // Use array syntax
The same applies for images and applets: using the name attribute in your HTML allows
you to refer to these objects by name in your JavaScript code.
As you might imagine, it is convenient to give names to frequently used Document
We'll see this technique
es in this and later chapters.
jects and Event Handlers
ts within it must respond to user
lers briefly in
Chapter 12
objects so that you can refer to them more easily in your scripts.
used a number of tim
14.1.5 Document Ob
To be interactive, an HTML document and the elemen
events. We discussed events and event hand
, and we've seen
vent
Chapter 19
several examples that use simple event handlers. We'll see many more examples of e
orking with Document objects. handlers in this chapter, because they are key to w
Unfortunately, we must defer a complete discussion of events and event handlers until
. For now, remember that event handlers are defined by attributes of HTML
elements, such as onclick and onmouseover. The values of these attributes should be
ay to define event handlers that we'll occasionally see
strings of JavaScript code. This code is executed whenever the specified event occurs on
the HTML element.
In addition, there is one other w
used in this and later chapters. We'll see in this chapter that Document objects such as
tes of Form and Image objects have JavaScript properties that match the HTML attribu
the and tags. For example, the HTML tag ha<form> <img> <img> s src and
i
width
dth properties.
ent
as a
ther example, consider the attribute of
mit
uppercase, lowercase, or mixed-case. In JavaScript, all event handler properties must be
written in lowercase.
ipt code to an event
g a function to an
:
/form>
that invokes a function and
ectly to the event handler
n name. That is because we don't want
here; we just want to assign a reference to it. As another example,
sider the following <a> tag and its onmouseover event handler:
er="status='Get Help Now!';">Help</a>
n to know that this <a> tag is the first one in the document, we can refer to the
ay
ocument.links[0].onmouseover = function( ) { status = 'Get Help
Now!'; }
See Chapter 19
attributes, and the JavaScript Image object has corresponding src and w
The same is true for event handlers. The HTML <a> tag supports an onclick ev
ject that represents a hyperlink hhandler, for example, and the JavaScript Link ob
corresponding property. As anoonclick onsubmit
the <form> element. In JavaScript, the Form object has a corresponding onsub
property. Remember that HTML is not case-sensitive, and attributes can be written in
In HTML, event handlers are defined by assigning a string of JavaScr
y are defined by assigninhandler attribute. In JavaScript, however, the
event handler property. Consider the following <form> and its onsubmit event handler
<form name="myform" onsubmit="return validateform( );">...<
In JavaScript, instead of using a string of JavaScript code
returns its result, we could simply assign the function dir
property like this:
document.myform.onsubmit = validateform;
Note that there are no parentheses after the functio
to
n
invoke the function
co
<a href="help.html" onmouseov
If we happe
corresponding Link object as document.links[0] and set the event handler this w
instead:
d
for a complete discussion of assigning event handlers in this way.
14.2 Dynamically Generated Documents
One of the most important features of the Document object (and perhaps of client-side
JavaScript in general) is the write( ) method, which allows you to dynamically
generate web-page content from your JavaScript programs. This method can be used in
two ways. The first and simplest way to use it is within a script, to output dynamically
generated HTML into the document that is currently being parsed. This was discussed in
Chapter 12. Consider the following code, which uses write( ) to add the current date
and the document's last-modified date to an otherwise static HTML document:
<script>
var today = new Date( );
document.write("<p>Document accessed on: " + today.toString( ));
document.write("<br>Document modified on: " + document.lastModified);
</script>
Using the write( ) method in this way is an extremely common JavaScript
.
u can use the write( ) method to output HTML to the
ile that document is being parsed. That is, you can call
within <script> tags only because these scripts are executed
cluding its event
ear as we
addition to adding dynamic content to the current document as it is being parsed,
on
g so can be a useful
th multiwindow or multiframe web sites. For example, JavaScript code in
a multiframe site might display a message in another frame with code like
ames[0].document.open( );
// Add some content to the document
parent.frames[0].document.write("<hr>Hello from your sibling
frame!<hr>");
// And close the document when we're done
parent.frames[0].document.close( );
</script>
To create a new document, we first call the open( ) method of the Document object,
then call write( ) any number of times to output the contents of the document, and
finally call the
close( ) method of the Document object to indicate that we have
finished. This last step is important; if you forget to close the document, the browser does
programming technique, and you'll see it in many scripts
Be aware, however, that yo
current document only wh
cument.write( ) fromdo
as part of the document parsing process. In particular, if you call document.write( )
invoked once the document has already from within an event handler and that handler is
been parsed, you will end up overwriting the entire document (in
handlers), instead of appending text to it. The reason for this will become cl
examine the second way to use the write( ) method.
In
write( ) can be used in conjunction with the open( ) and close( ) Document
methods to create entirely new documents within a window or frame. Although you
eascannot usefully write to the current document from an event handler, there is no r
why you can't write to a document in another window or frame; doin
technique wi
ne frame ofo
this:
<script>
// Start a new document, erasing any content that was already in
frames[0]
parent.fr
not stop the document loading animation it displays. Also, the browser may buffer the
HTML you have written; it is not required to display the buffered output until you
explicitly end the document by calling close( ).
In contrast to the close( ) call, which is required, the open( ) call is optional. If you
call the write( ) method on a document that has already been closed, JavaScript
implicitly opens a new HTML document, as if you had called the open( ) method. This
explains what happens when you call document.write( ) from an event handler within
the same document -- JavaScript opens a new document. In the process, however, the
current document (and its contents, including scripts and event handlers) is discarded.
This is never what you want to do, and it can even cause some early browsers (such as
Netscape 2) to crash. As a general rule of thumb, a document should never call write( )
er, just as if they had been concatenated. So
instead of writing:
document.write("Hello, " + username + " Welcome to my home page!");
document.write(greeting, username, welcome);
ct also
very way
nores line
b ually doesn't make a difference, but as we'll see in a bit,
the
writeln( ) method can be convenient when you're working with non-HTML
on itself from within an event handler.
A couple of final notes about the write( ) method. First, many people do not realize
that the write( ) method can take more than one argument. When you pass multiple
arguments, they are output one after anoth
you might equivalently write:
var greeting = "Hello, ";
var welcome = " Welcome to my home page!";
The second point to note about the write( ) method is that the Document obje
supports a writeln( ) method, which is identical to the write( ) method in e
t it appends a newline after outputting its arguments. Since HTML igexcept tha
reaks, this newline character us
documents.
Example 14-1 shows how you might create a complex dialog box with the Window
open( ) method and the methods of the Document object. This example registers an
onerror event handler function for the window; the function is invoked when a
JavaScript error occurs. The error handler function creates a new window and uses the
Document object methods to create an HTML form within the window. The form allows
the user to see details about the error that occurred and email a bug report to the aut
the JavaScript code.
hor of
Figure 14-1 shows a sample window. Recall from the discussion of the onerror error
hapter 13handler in C that Netscape 6 does not pass the correct arguments to the error
handler function. For this reason, the output on Netscape 6 does not match what is
illustrated here.
Figure 14-1. Using a browser window as a dialog box
ydomain.com";
// Define the error handler. It generates an HTML form so the user
// can report the error to the author.
function report_error(msg, url, line)
{
var w = window.open("", // URL (none specified)
"error"+error_count++, // Name (force it to be
unique)
"resizable,status,width=625,height=400"); //
Features
// Get the Document object of the new window
Example 14-1. Dynamically creating a dialog window
<script>
// A variable we use to ensure that each error window we create is
unique
var error_count = 0;
// Set this variable to your email address
var email = "myname@m
var d = w.document;
// Output an HTML document, including a form, into the new window
// Note that we omit the optional call to document.open( )
d.write('<div align="center">');
d.write('<font size="7" face="helvetica"><b>');
d.write('OOPS.... A JavaScript Error Has Occurred!');
d.write('</b></font><br><hr size="4" width="80%">');
tion="mailto:' + email + '" method=post');
<input type="submit" value="Report Error"> ');
write('<input type="button" value="Dismiss" onclick="self.close(
);">');
d.write('</div><div align="right">');
'+line +'">');
when we're done
d.close( );
// Return true from this error handler, so that JavaScript does not
Document open( ) method with no arguments, it opens a new HTML
document. Remember, though, that web browsers can display a number of other data
d.write('<form ac
d.write(' enctype="text/plain">');
d.write('<font size="3">');
d.write('<i>Click the "Report Error" button to send a bug
report.</i><br>');
.write(' d
d.
d.write('<br>Your name <i>(optional)</i>: ');
d.write('<input size="42" name="name" value="">');
d.write('<br>Error Message: ');
d.write('<input size="42" name="message" value="' + msg + '">');
d.write('<br>Document: <input size="42" name="url" value="' + url +
'">');
d.write('<br>Line Number: <input size="42" name="line"
value="
d.write('<br>Browser Version: ');
d.write('<input size="42" name="version"
value="'+navigator.userAgent+'">');
d.write('</div></font>');
d.write('</form>');
// Remember to close the document
// display its own error dialog box
return true;
}
// Before the event handler can take effect, we have to register it
// for a particular window
self.onerror = report_error;
</script>
<script>
// The following line of code purposely causes an error as a test
alert(no_such_variable);
</script>
14.2.1 Non-HTML Documents
When you call the
formats besides HTML text. When you want to dynamically create and display a
document using some other data format, you call the open( ) method with a single
argument, which is the MIME type you desire.
[1]
[1]
This argument to the method has not been standardized by the W3C DOM. It works in IEopen( ) 4 and later, and in Netscape 3 and 4.
e 6: only HTML documents are supported by that browser. Surprisingly, it does not work in Netscap