User:Moncur/04

Ka Wiktionary

4. Working with the Document Object Model (DOM)[wax ka badal]

Understanding the Document Object Model (DOM)[wax ka badal]

One advantage that JavaScript has over basic HTML is that scripts can manipulate the web document and its contents. Your script can load a new page into the browser, work with parts of the browser window and document, open new windows, and even modify text within the page dynamically.

To work with the browser and documents, JavaScript uses a hierarchy of parent and child objects called the Document Object Model (DOM). These objects are organized into a tree-like structure, and represent all of the content and components of a web document.

By the Way
The DOM is not part of the JavaScript language, rather, it's an API (application programming interface) built in to the browser. While the DOM is most often used with JavaScript, it can also be used by other languages, such as VBScript and Java.

The objects in the DOM have properties, variables that describe the web page or document, and methods, functions that enable you to work with parts of the web page.

When you refer to an object, you use the parent object name followed by the child object name or names, separated by periods. For example, JavaScript stores objects to represent images in a document as children of the document object. The following refers to the image9 object, a child of the document object, which is a child of the window object:

window.document.image9

The window object is the parent object for all of the objects we will be looking at in this hour. Figure 4.1 shows this section of the DOM object hierarchy and a variety of its objects.

By the Way
This diagram only includes the basic browser objects that will be covered in this hour. These are actually a small part of the DOM, which you'll learn more about in Part III, "Learning More About the DOM."

History of the DOM[wax ka badal]

Starting with the introduction of JavaScript 1.0 in Netscape 2.0, browsers have included objects that represent parts of a web document and other browser features. However, there was never a true standard. While both Netscape and Microsoft Internet Explorer included many of the same objects, there was no guarantee that the same objects would work the same way in both browsers, let alone in less common browsers.

The bad news is that there are still differences between the browsers, but here's the good news. Since the release of Netscape 3.0 and Internet Explorer 4.0, all of the basic objects (those covered in this hour) are supported in much the same way in both browsers. With more recent browser releases, a much more advanced DOM is supported.

DOM Levels[wax ka badal]

The W3C (World Wide Web Consortium) developed the DOM level 1 recommendation. This is a standard that defines not only basic objects, but an entire set of objects that encompass all parts of an HTML document. A level 2 DOM standard has also been released, and level 3 is under development.

Netscape 4 and Internet Explorer 4 supported their own DOMs that allowed more control over documents, but weren't standardized. Fortunately, starting with Internet Explorer 5 and Netscape 6, both support the W3C DOM, so you can support both browsers with simple, standards-compliant code. All of today's current browsers support the W3C DOM.

The basic object hierarchy described in this hour is informally referred to as DOM level 0, and the objects are included in the DOM level 1 standard. You'll learn how to use the W3C DOM to work with any part of a web document later in this book.

Did you Know?
The W3C DOM allows you to modify a web page in real time after it has loaded. You'll learn how to do this in Part III.

Using window Objects[wax ka badal]

At the top of the browser object hierarchy is the window object, which represents a browser window. You've already used at least one method of the window object: the window.alert() method, or simply alert(), displays a message in an alert box.

There can be several window objects at a time, each representing an open browser window. Frames are also represented by window objects. You'll learn more about windows and frames in Hour 10, "Using Windows and Frames."

By the Way
Layers, which enable you to include, modify, and position dynamic content within a web document, are also similar to window objects. These are explained in Hour 13, "Using the W3C DOM."

Working with Web Documents[wax ka badal]

The document object represents a web document, or page. Web documents are displayed within browser windows, so it shouldn't surprise you to learn that the document object is a child of the window object.

Because the window object always represents the current window (the one containing the script), you can use window.document to refer to the current document. You can also simply refer to document, which automatically refers to the current window.

By the Way
You've already used the document.write method to display text within a web document. The examples in earlier hours only used a single window and document, so it was unnecessary to use window.document.writebut this longer syntax would have worked equally well.

If multiple windows or frames are in use, there might be several window objects, each with its own document object. To use one of these document objects, you use the name of the window and the name of the document.

In the following sections, you will look at some of the properties and methods of the document object that will be useful in your scripting.

Getting Information About the Document[wax ka badal]

Several properties of the document object include information about the current document in general:

  • document.URL specifies the document's URL. This is a simple text field. You can't change this property. If you need to send the user to a different location, use the window.location object, described later in this hour.
  • document.title lists the title of the current page, defined by the HTML <title> tag.
  • document.referrer is the URL of the page the user was viewing prior to the current pageusually, the page with a link to the current page.
  • document.lastModified is the date the document was last modified. This date is sent from the server along with the page.
  • document.bgColor and document.fgColor are the background and foreground (text) colors for the document, corresponding to the BGCOLOR and TEXT attributes of the <body> tag.
  • document.linkColor, document.alinkColor, and document.vlinkColor are the colors for links within the document. These correspond to the LINK, ALINK, and VLINK attributes of the <body> tag.
  • document.cookie enables you to read or set a cookie for the document. See http://www.jsworkshop.com/cookies.html for information about cookies.

As an example of a document property, Listing 4.1 shows a short HTML document that displays its last modified date using JavaScript.

Listing 4.1. Displaying the Last Modified Date
<html><head><title>Test Document</title></head>
<body>
<p>This page was last modified on:
<script language="JavaScript" type="text/javascript">
document.write(document.lastModified);
</script>
</p>
</body>
</html>

This can tell the user when the page was last changed. If you use JavaScript, you don't have to remember to update the date each time you modify the page. (You could also use the script to always print the current date instead of the last modified date, but that would be cheating.)

By the Way
You might find that the document.lastModified property doesn't work on your web pages, or returns the wrong value. The date is received from the web server, and some servers do not maintain modification dates correctly.

Writing Text in a Document[wax ka badal]

The simplest document object methods are also the ones you will use most often. In fact, you've used one of them already. The document.write method prints text as part of the HTML page in a document window. This statement is used whenever you need to include output in a web page.

An alternative statement, document.writeln, also prints text, but it also includes a newline (\n) character at the end. This is handy when you want your text to be the last thing on the line.

Watch Out!
Bear in mind that the newline character is displayed as a space by the browser, except inside a <pre> container. You will need to use the <br> tag if you want an actual line break.

You can use these methods only within the body of the web page, so they will be executed when the page loads. You can't use these methods to add to a page that has already loaded without reloading it.

By the Way
You can also directly modify the text of a web page on newer browsers using the features of the new DOM. You'll learn these techniques in Hour 14.

The document.write method can be used within a <script> tag in the body of an HTML document. You can also use it in a function, provided you include a call to the function within the body of the document.

Using Links and Anchors[wax ka badal]

Another child of the document object is the link object. Actually, there can be multiple link objects in a document. Each one includes information about a link to another location or an anchor.

Did you Know?
Anchors are named places in an HTML document that can be jumped to directly. You define them with a tag like this: <a name="part2">. You can then link to them: <a href="#part2">.

You can access link objects with the links array. Each member of the array is one of the link objects in the current page. A property of the array, document.links.length, indicates the number of links in the page.

Each link object (or member of the links array) has a list of properties defining the URL. The href property contains the entire URL, and other properties define portions of it. These are the same properties as the location object, defined later in this hour.

You can refer to a property by indicating the link number and property name. For example, the following statement assigns the entire URL of the first link to the variable link1:

link1 = links[0].href;

The anchor objects are also children of the document object. Each anchor object represents an anchor in the current documenta particular location that can be jumped to directly.

Like links, you can access anchors with an array: anchors. Each element of this array is an anchor object. The document.anchors.length property gives you the number of elements in the anchors array.

Accessing Browser History[wax ka badal]

The history object is another child (property) of the window object. This object holds information about the URLs that have been visited before and after the current one, and it includes methods to go to previous or next locations.

The history object has one property you can access:

  • history.length keeps track of the length of the history listin other words, the number of different locations that the user has visited.
By the Way
The history object has current, previous, and next properties that store URLs of documents in the history list. However, for security and privacy reasons, these objects are not normally accessible in today's browsers.

The history object has three methods you can use to move through the history list:

  • history.go() opens a URL from the history list. To use this method, specify a positive or negative number in parentheses. For example, history.go(-2) is equivalent to pressing the Back button twice.
  • history.back() loads the previous URL in the history listequivalent to pressing the Back button.
  • history.forward() loads the next URL in the history list, if available. This is equivalent to pressing the Forward button.

You'll use these methods in the Try It Yourself section at the end of this hour.

Working with the location Object[wax ka badal]

A third child of the window object is the location object. This object stores information about the current URL stored in the window. For example, the following statement loads a URL into the current window:

window.location.href="http: //www.starlingtech.com";

The HRef property used in this statement contains the entire URL of the window's current location. You can also access portions of the URL with various properties of the location object. To explain these properties, consider the following URL:

http: //www.jsworkshop.com:80/test.cgi?lines=1#anchor

The following properties represent parts of the URL:

  • location.protocol is the protocol part of the URL (http: in the example).
  • location.hostname is the host name of the URL ([http: //www.jsworkshop.com/ www.jsworkshop.com] in the example).
  • location.port is the port number of the URL (80 in the example).
  • location.pathname is the filename part of the URL (test.cgi in the example).
  • location.search is the query portion of the URL, if any (lines=1 in the example). Queries are used mostly by CGI scripts.
  • location.hash is the anchor name used in the URL, if any (#anchor in the example).

The link object, introduced earlier this hour, also includes this list of properties for accessing portions of the URL.

By the Way
Although the location.href property usually contains the same URL as the document.URL property described earlier in this hour, you can't change the document.URL property. Always use location.href to load a new page.

The location object has two methods:

  • location.reload() reloads the current document. This is the same as the Reload button on the browser's toolbar. If you optionally include the true parameter, it will ignore the browser's cache and force a reload whether the document has changed or not.
  • location.replace() replaces the current location with a new one. This is similar to setting the location object's properties yourself. The difference is that the replace method does not affect the browser's history. In other words, the Back button can't be used to go to the previous location. This is useful for splash screens or temporary pages that it would be useless to return to.
Try It Yourself
Creating Back and Forward Buttons

You can use the back and forward methods of the history object to add your own Back and Forward buttons to a web document. The browser already has Back and Forward buttons, of course, but it's occasionally useful to include your own links that serve the same purpose.

You will now create a script that displays Back and Forward buttons and use these methods to navigate the browser. Here's the code that will create the Back button:

<input type="button"
 onClick="history.back();" value="<-- Back">

The <input> tag defines a button labeled Back. The onClick event handler uses the history.back() method to go to the previous page in history. The code for the Forward button is similar:

<input type="button"
onClick="history.forward();" value="Forward -->">

With these out of the way, you just need to build the rest of the HTML document. Listing 4.2 shows the complete HTML document, and Figure 4.2 shows a browser's display of the document. After you load this document into a browser, visit other URLs and make sure the Back and Forward buttons work.

Listing 4.2. A Web Page That Uses JavaScript to Include Back and Forward Buttons
<html>
<head><title>Back and Forward Buttons</title>
</head>
<body>
<h1> Back and Forward Buttons</h1>
<p>This page allows you to go back or forward to pages in the  history list.
These should be equivalent to the back and forward arrow buttons in the
browser's toolbar.</p>
<p>
<input type="button"
 onClick="history.back();" value="<-- Back">
<input type="button"
 onClick="history.forward();" value="Forward  ->">
</p>
</body>
</html>

Summary[wax ka badal]

In this hour, you've learned about the Document Object Model (DOM), JavaScript's hierarchy of web page objects. You've learned how you can use the document object to work with documents, and used the history and location objects to control the current URL displayed in the browser.

You should now have a basic understanding of the DOM and some of its objectsyou'll learn about more of the objects throughout this book.

Congratulations! You've reached the end of Part I of this book. In Part II, you'll get back to learning the JavaScript language, starting with Hour 5, "Using Variables, Strings, and Arrays."

Q&A[wax ka badal]

Q1:

I can use history and document instead of window.history and window.document. Can I leave out the window object in other cases?

A1:

Yes. For example, you can use alert instead of window.alert to display a message. The window object contains the current script, so it's treated as a default object. However, be warned that you shouldn't omit the window object's name when you're using frames, layers, or multiple windows, or in an event handler.

Q2:

I used the document.lastModified method to display a modification date for my page, but it displays a date in 1970, or a date that I know is incorrect. What's wrong?

A2:

This function depends on the server sending the last modified date of the document to the browser. Some web servers don't do this properly, or require specific file attributes in order for this to work.

Q3:

Can I change history entries, or prevent the user from using the Back and Forward buttons?

A3:

You can't change the history entries. You can't prevent the use of the Back and Forward buttons, but you can use the location.replace() method to load a series of pages that don't appear in the history. There are a few tricks for preventing the Back button from working properly, but I don't recommend themthat's the sort of thing that gives JavaScript a bad name.

Quiz Questions[wax ka badal]

Test your knowledge of JavaScript by answering the following questions:

1.

Which of the following objects can be used to load a new URL into the browser window?

document.url

window.location

window.url

2.

Which object contains the alert() method?

window

document

location

3.

Which of the following DOM levels describes the objects described in this hour?

DOM level 0

DOM level 1

DOM level 2

Quiz Answers[wax ka badal]

1.

b. The window.location object can be used to send the browser to a new URL.

2.

a. The window object contains the alert() method.

3.

a. The objects described in this hour fall under the informal DOM level 0 specification.

Exercises[wax ka badal]

To further explore the JavaScript features you learned about in this hour, you can perform the following exercises:

  • Modify the Back and Forward example in Listing 4.2 to include a Reload button along with the Back and Forward buttons. (This button would trigger the location.reload() method.)
  • Modify the Back and Forward example to display the current number of history entries.

-->