11.1 The Document Object Model


In Chapter 10 we addressed the browser object model. The properties and methods of different browsers vary since there is no standard for defining what a browser does. The document object model (DOM), on the other hand, deals specifically with a document, and there are now standards that dictate how the objects in an HTML (or XML) page should be represented. The DOM is a hierarchical tree-like structure,consisting of a collection of objects, all relating to the document. According to the World Wide Web Consortium (WC3), a DOM is a platform- and language-independent object model that "allows programs and scripts to dynamically access and update the content, structure, and style of documents." [1] It mimics the structure of the document it models. When working with JavaScript, the DOM mimics the HTML document. Each element of an HTML document, such as an image, form, link, or button, can be represented as a JavaScript object, and each object contains properties and methods to describe and manipulate these objects. (See http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html for more on HTML-specific DOMs.)

[1] World Wide Web Consortium (W3C), http://www.w3.org/DOM/.

The W3C abstract states: "The Document Object Model provides a standard set of objects for representing HTML and XML documents, a standard model of how these objects can be combined, and a standard interface for accessing and manipulating them. Vendors can support the DOM as an interface to their proprietary data structures and APIs, and content authors can write to the standard DOM interfaces rather than product-specific APIs, thus increasing interoperability on the Web." [2]

[2] World Wide Web Consortium (W3C), http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/.

The W3C defines DOM Level 1 to create an industry standard for all browsers, fully supported by Netscape 6 and Internet Explorer 5 and 6. The standard consists of two parts : the first defines how to navigate and manipulate the HTML and XML structure for the core objects, properties, and methods; the second defines a set of objects strictly related to HTML. In addition to DOM Level 1, there are two other levels, still in progress. What all that boils down to is that the DOM specifies a standard set of objects that will work with HTML and XML documents no matter what browser, no matter what scripting language.

Example 11.1 shows an HTML document and how it is represented structurally.

Example 11.1
 (The HTML Document) <html>    <head>       <title>My Page</title>    </head>    <body>       <h1>Level 1</h1>       <h2>Level 2</h2>       <h3>Level 3</h3>    </body> </html> (The DOM as a Tree) graphics/11inf02.gif 

The DOM hierarchy ”a tree structure, similar to a family tree ”consists of parents and children called nodes (no, not nerds, but nodes). Each leaf in the tree is called a node. The topmost node, the <html> tag, is the root node. The <head> and <body> tags are child nodes of the <html> parent node. If the nodes are at the same level, they are called siblings, like a real family. Nodes may have a parent and a number of child nodes. The DOM provides a set of objects, with properties and methods, that allow access to this tree structure within a JavaScript program. With the advent of dynamic HTML, the DOM has control over every element of a Web page, and specifies base objects such as Node, NodeList , and NamedNodeMap , and high-level objects to represent all elements of the document. We'll see more on dynamic HTML and the DOM in Chapter 15, "Dynamic HTML: Style Sheets, the DOM, and JavaScript." For now we will use the DOM to navigate through the document object and its children, and see how to manipulate these objects with their many properties and methods.

11.1.1 The JavaScript Hierarchy

Since the JavaScript document objects are arranged in a DOM hierarchy, each node in the tree can be referenced using the dot syntax. In JavaScript, the window object is at the top of the tree, the ultimate parent because everything takes place within the window. The window is called the top, self , or parent object. It has child nodes. They are listed below:

  1. The navigator object

  2. The frames object

  3. The history object

  4. The location object

  5. The document object

  6. The screen object

  7. The event object

We discussed the window as part of the browser object model in the last chapter. The DOM is concerned only with those nodes that make up the document object. Documents contain text, images, forms, links, etc. The most commonly used object is the document object . Subordinate to the document object are another set of objects, its children:

  1. The anchors object

  2. The images object

  3. The forms object

  4. The links object

  5. The applets object

  6. The embeds object

Figure 11.1. The document model.

graphics/11fig01.gif

Revisiting the Dot Syntax

To refer to an object, you start with the window object ( parent ), followed by a dot, then the next object in the hierarchy, then another dot, and so on until you reach the desired object; for example, window.location or window.document.forms[0] . When referencing a child of the window object it is not necessary to include the window , because JavaScript knows that the window is at the top of the tree. Instead of saying window.document. bgColor , you can simply say document.bgColor .

11.1.2 The Document Itself

The document object is a property of the window object, and if the window is partitioned into frames (subwindows), each frame is a property of the window object.

Every window (or frame) contains a document object that corresponds to the HTML document shown in the window. This object corresponds mainly to the body of the document ”that is, what is inserted between the <body></body> tags ”although it can also be found in a limited way within the <head></head> tags. JavaScript programs manipulate this object to bring life to otherwise dead, static pages. Since the document object is below the window object, the document object can be represented as a property of the window by saying window.document . The forms object is an array of objects below the document object, so the forms object is a property of the document object and is represented as window.document.forms[] .

As stated before, because the window object is at the top of the hierarchy, any objects just below it, such as the document or location objects, are window properties and the word window is not required; thus, specifying window.document.bgColor is the same as document.bgColor.

The syntax for describing the background color ( bgcolor ) property for a document object is shown in the following example:

 
 document.bgColor = "yellow"; 
Document Properties

The document object is defined when the HTML <body> tag is encountered on the page and stays in existence until the page is unloaded, and the <body> tag has a number of attributes that define the appearance of the page. The document object has properties that correspond to the HTML <body> tag attributes, as shown in Tables 11.1 and 11.2. The properties of the document object are shown in the output of Example 11.2. (See Chapter 12, "Handling Events," for events that are associated with the <body> tag.)

Table 11.1. HTML <body> tag attributes.

Attribute

What It Specifies

alink

Color of an active link; i.e., while the mouse is on the link

background

URL of a background image

bgcolor

Background color of the page

fgcolor

Text or foreground color

link

Color of an unvisited link

vlink

Color of a visited link

Table 11.2. Some document object properties.

Property

What It Describes

anchors[]

An array of anchors objects

applets[]

An array of applets objects, relating to Java applets

bgColor, fgColor

Determines the background color and text color, related to the HTML <body> tag

cookie

Allows reading and writing HTTP cookies (see Chapter 14, "Cookies")

domain

A security property for Web servers in the same domain

forms[]

An array of forms objects, related to the HTML <form> tag

images[]

An array of images objects, related to the HTML <img> tag

lastModified

A string with the date when the page was last modified

linkColor, alinkColor, vlinkColor

Determines the color of unvisited links, active links, and visited links, respectively; related to link attributes of the HTML <body> tag

links[]

An array of links objects, related to the HTML <a href> tags

location

The URL of the document (deprecated)

referrer

URL of the document that linked the browser to this document

title

The title of the current document, related to the text between the <title></title> tags found in the head of the document

URL

A string containing the URL of the document

Example 11.2
 <html><head><title>Looping through Object Properties</title></head>    <body>    <script language="JavaScript"> 1      var props=new Array(); 2      for ( var property in window.document){ 3         props.push(property);        } 4      for(i=0;i<props.length; i++){ 5         document.write( props[i] + " ");           if( i>0 && i%3 == 0 ){               document.write("<br>");           }        }    </script>    </body></html> 

EXPLANATION

  1. A new array object called props is created with the Array() constructor.

  2. The for/in loop allows you to enumerate (list one by one) the properties of an object, in this case the document object. The body of the for/in loop is executed once for each property of the document object. If a property has been flagged as read-only, it will not be listed.

  3. Each time through the loop, a new property of the document object is pushed onto the props array.

  4. This for loop iterates through the props array to list the properties that were assigned to it.

  5. Each property of the document object is displayed in groups of three. The output differs somewhat on different browsers.

Figure 11.2. Using the for/in loop to display the properties of the document object.

graphics/11fig02.jpg

Using the document Object Properties in JavaScript

The following example demonstrates how the properties that describe the document are used in a JavaScript program. The write() method displays a description of each of these properties as they pertain to the current document. The background color is silver, the text is forest green, the unvisited link is blue, and the visited link is purple.

Example 11.3
 <html><head><title>Document Object Properties</title></head>  <body bgColor="silver" text="forestgreen" link="blue"   vlink="purple">  <font face="arial" size="+2">     <script language="JavaScript">        var beg_tag="<em>"; end_tag="</em><br>";        document.write("The location of the document"+ beg_tag + 1  document.location  + end_tag);        document.write("The document's title: "+ beg_tag+ 2  document.title  + end_tag);        document.write("The background color: "+ beg_tag+ 3  document.bgColor  + end_tag);        document.write("The link color is: "+ beg_tag+ 4  document.linkColor  + end_tag);        document.write("The text color is: "+ beg_tag+ 5  document.fgColor  + end_tag);        document.write("The document was last modified: "+ beg_tag + 6  document.lastModified  + end_tag);     </script> 7   <a href="thanks.stm">Thanks!</a>     </body></html> 

EXPLANATION

  1. This property contains the location of the document; i.e., the full path name to the document.

  2. This property contains the title of the document, shown in the title bar at the top of the window.

  3. This property describes the hexidecimal color of the document's background, in this example, silver.

  4. This property describes the hexidecimal color of links, blue in this example.

  5. This property describes the hexidecimal color of the text, forest green in this example.

  6. This displays the date and time when the document was last modified.

  7. The link will change color from blue to purple once it has been visited. Complete output is shown in Figure 11.3.

    Figure 11.3. Document properties. Output from Example 11.3.

    graphics/11fig03.jpg

The document Object Methods

The document object has methods to tell the object how to behave or what to do. Table 11.3 lists these methods. We have used the write() and writeln () methods throughout this text to send output to the screen dynamically, as shown below:

 
 document.writeln("<h2>Welcome to the JavaScript World!</h1>"); 

Methods, like properties, use the dot syntax to define the object they are manipulating; for instance, document.clear() or window. open (). (The parentheses differentiate a method from a property.)

Table 11.3. Methods of the document object.

Method

What It Does

clear()

Clears the current document window

close()

Closes the document window for writing

focus()

Brings the document into focus

open()

Begins a new document, erasing the old one

write()

Writes and appends text into the current document

writeln()

Same as write() , but appends a newline if in a <pre> tag

When you open a new document, the current document will be replaced with a new document and all of its content overwritten. Example 11.4 opens a new document in an existing frame. The original text in the document is overwritten. After the document is opened, it must be closed.

Example 11.4
 <html>     <head><title>Frame Me!</title></head>  <!-- Creating the framesets for two files -->   <!-- This HTML file is named: framedef.html -->  <frameset cols="25%,75%">     <frame src="leftframe.html"  name=lframe>     <frame src="rightframe.html" name=rframe>     </frameset>     </html>     ---------------------------------------------------------------     <html>     <head><title>Right Frame</title></head>  <!-- This file is named: rightframe.html -->  <body bgColor="lightgreen">     <h2>     Just to show you that this is the right frame     </h2>     </body>     </html>     ---------------------------------------------------------------     <html>  <!-- This file is named: leftframe.html -->  <head><title>Left Frame</title></head>     <body bgColor="yellow"><font face="verdana">     <h2>     left frame writes to right frame     </h2>     <script language="JavaScript">         //  Methods of the document object  1  parent.frames[1].document.open();  2  parent.frames[1].document.write(  "<body bgcolor='black'>",                "<font color='white'>",                "<h1>Hey brother, let me write all over you!</h2>"); 3  parent.frames[1].document.close();  </script>     </body>     </html> 

EXPLANATION

  1. From the left frame, parent.frames[0] , the right frame is referenced as parent.frames[1] . A new document is opened in the right-hand frame with the open() method. Whatever was in that frame is erased by the new document. The open() method is optional because when the write() method is called, JavaScript will automatically open a new document and send the output there. There are times when this might happen, and you didn't want to overwrite everything. Since the document is parsed top to bottom, if the browser has finished parsing, then any attempts to write to the document will cause the whole thing to be overwritten. This might happen if you call a function as a result of some event being triggered.

  2. The write() method sends content to the right-hand frame, including the background color, the color of the font, and a string of text. Take note that the write() [and writeln() ] methods take a comma-separated list of arguments. In previous examples, we used the + (the concatenation operator) to join the strings together, but here, commas are used to separate the strings. The write() method displays its arguments in the order they are given.

  3. The document in the right-hand frame is officially closed. Whereas the open() method was optional, the close() method is required. When using Internet Explorer, the content of the frame remained unchanged after closing the frame, but with Netscape, the old document reappeared. See Figures 11.4 and 11.5.

    Figure 11.4. Left frame opened a new document in right frame, replacing what was there.

    graphics/11fig04.jpg

    Figure 11.5. After the document in the right-hand frame is closed, the original document reappears (Netscape 7).

    graphics/11fig05.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net