home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

Chapter 14. The Document Object

Every Window object has a document property. This property refers to a Document object that represents the HTML document displayed in the window. The Document object is probably the most commonly used object 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 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 displayed, and so on.

Client-side JavaScript exists to turn static HTML documents into interactive programs -- it is the Document object that gives JavaScript interactive access to the content of otherwise static documents. In addition to the properties that provide information about a 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 that represent all the HTML forms in the document. And the images[] and applets[] arrays contain objects that represent the images and applets in the document. These arrays and the objects they contain open up a world of possibilities for client-side JavaScript programs, and the bulk of this chapter is devoted to documenting them.

This chapter covers the core features of the Document object that are implemented by virtually every JavaScript-enabled browser. Newer browsers, such as IE 4 and later and Netscape 6 and later, implement a full document object model, or DOM, that gives JavaScript complete access to and control over all document content. These advanced 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.2. Document Properties

The Document object defines the following properties:

alinkColor , linkColor, vlinkColor
These properties describe the colors of hyperlinks. linkColor is the normal color 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.

anchors[]
An array of Anchor objects that represent the anchors in the document.

applets[]
An array of Applet objects that represent 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
A special property that allows JavaScript programs to read and write HTTP cookies. See Chapter 16 for details.

domain
A property that allows mutually trusted web servers within the same Internet domain to collaboratively relax certain security restrictions on interactions between their web pages. See 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
A string that contains the modification date of the document.

links[]
An array of Link objects that represent the hypertext links in the document.

location
A deprecated synonym for the URL property.

referrer
The URL of the document containing the link that brought the browser to the current document, if any.

title
The text between the <title> and </title> tags for this document.

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 http://www.w3.org) has standardized a DOM and issued two versions of this standard, known as Level 1 and 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 universal implementation, however, it is a de facto standard and is often referred to as the Level 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. Furthermore, the Document object methods and properties listed previously have been formalized as part of the Level 1 DOM, so they are guaranteed to remain supported by future browsers.

One important thing to understand about the W3C DOM 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 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 objects so that you can refer to them more easily in your scripts. We'll see this technique used a number of times in this and later chapters.

14.1.5. Document Objects and Event Handlers

To be interactive, an HTML document and the elements within it must respond to user events. We discussed events and event handlers briefly in Chapter 12, and we've seen several examples that use simple event handlers. We'll see many more examples of event handlers in this chapter, because they are key to working with Document objects.

Unfortunately, we must defer a complete discussion of events and event handlers until Chapter 19. 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 strings of JavaScript code. This code is executed whenever the specified event occurs on the HTML element.

In addition, there is one other way to define event handlers that we'll occasionally see used in this and later chapters. We'll see in this chapter that Document objects such as Form and Image objects have JavaScript properties that match the HTML attributes of the <form> and <img> tags. For example, the HTML <img> tag has src and width attributes, and the JavaScript Image object has corresponding src and width properties. The same is true for event handlers. The HTML <a> tag supports an onclick event handler, for example, and the JavaScript Link object that represents a hyperlink has a corresponding onclick property. As another example, consider the onsubmit attribute of the <form> element. In JavaScript, the Form object has a corresponding onsubmit property. Remember that HTML is not case-sensitive, and attributes can be written in uppercase, lowercase, or mixed-case. In JavaScript, all event handler properties must be written in lowercase.

In HTML, event handlers are defined by assigning a string of JavaScript code to an event handler attribute. In JavaScript, however, they are defined by assigning a function to an event handler property. Consider the following <form> and its onsubmit event handler:

<form name="myform" onsubmit="return validateform( );">...</form> 

In JavaScript, instead of using a string of JavaScript code that invokes a function and returns its result, we could simply assign the function directly to the event handler property like this:

document.myform.onsubmit = validateform;  

Note that there are no parentheses after the function name. That is because we don't want to invoke the function here; we just want to assign a reference to it. As another example, consider the following <a> tag and its onmouseover event handler:

<a href="help.html" onmouseover="status='Get Help Now!';">Help</a> 

If we happen to know that this <a> tag is the first one in the document, we can refer to the corresponding Link object as document.links[0] and set the event handler this way instead:

document.links[0].onmouseover = function( ) { status = 'Get Help Now!'; }

See Chapter 19 for a complete discussion of assigning event handlers in this way.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.