The Document Object Model, the main source of objects for JavaScript, puts an object interface on both the HTML document and the browser. JavaScript can interact with the browser to load a new page, examine the browser's historypreviously loaded Web pagesor interact with pages in neighboring frames.
The principal object to use when working with document content is the document object. A reference to it can be obtained through the document property of the window object, which is a globally available object in any JavaScript function. JavaScript uses "dot notation" to navigate through the properties and references associated with the document. For example, the following JavaScript function initializes a text field in a form with the current day of the week:
today = new Date(); weekdays = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"); dow = weekdays[today.getDay()]; window.document.forms["demo"].elements["inday"].value = dow;
In this script fragment, the variable today is set to the current date. An array of all possible weekdays is defined in the variable weekdays. The current day of the week is obtained by calling the getDay() method of the Date object, which returns an integer indicating the day of the week. This value is used to index into the weekdays array to obtain the current day of the week as a string and to assign it to the dow variable. The last line sets the value of a field in a form. The form is named "demo", and the field is an input text control named "inday".
To access the field and to set its value property, the object hierarchy is navigated by beginning with the window object, a browser-supplied global object that more or less represents the browser itself. This object has a property, called the document, which represents the HTML Web page. The document object has a forms collection, since it is possible to define multiple forms in a page. This collection of forms is indexed by the name of the form: "demo". Forms contain form elements, or input fields, that can be accessed by indexing the elements collection of the form object. Once a reference to the field is obtained, its value property is set with the current day of the week.
Most JavaScript interactions behave in this way, first performing the business logic calculations and then accessing the appropriate DOM interfaces to update the document. The trick to using JavaScript is gaining an understanding of the objects and interfaces you have to work with. The Document Object Model standard is a good place to start. It defines the object hierarchy that page scripts use to access the information in the document and even the browser itself. Figure 3-4 shows the object hierarchy available to scripts in a page.
Figure 3-4. The DOM hierarchy
Overview of Modeling and Web-Related Technologies
Building Web Applications