JavaScript - Navigator & Document Object

In previous tutorial we talk about Window Object and Location Object little bit now let’s get dive into Navigator object and then Document Object.

The Navigator Object:

Name said that it is used for Netscape Navigator branded browser, but the navigator object is implemented in all scriptable browsers.

All browsers also implement a handful of properties that reveal the same kind of information that browsers send to servers with each page request. Thus, the navigator.userAgent property returns a string text with numerous details about the browser and operating system.

For example, a script running in Internet Explorer 6 in Windows XP receives the following value for the navigator.userAgent property:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461).

The Document Object :

The document object holds the real content of the page. Properties and methods of the document object generally affect the look and content of the document that occupies the window.

All W3C DOM-compatible browsers (and IE4) allow script access to the text contents of a page once the document has loaded. The document.write() method lets a script dynamically create content as the page loads on any browser.

Many document object properties are arrays of other objects in the document, which provide additional ways to reference these objects (over and above the document.getElementById() method).

Accessing a document object’s properties and methods is straightforward, as shown in the following syntax examples:
            [window.]document.propertyName
            [window.]document.methodName([parameters])

Document.Forms[] Property

It is convenient that the document object contains a property—document.forms— whose value is an array of all form element objects in the document.

We seen in Arrays Tutorial ,an index number inside an array’s square brackets points to one of the elements in the array.

To find out how many form objects are in the current document, use document.forms.length

To access the first form in a document, for example, the reference is
                document.forms[0]

As a further convenience, all scriptable browsers let you reference a form more directly by its name (that is, the identifier assigned to the name attribute of the <form> tag) in one of two ways. The first way is via array syntax, applying the form’s name as a string index value of the array:
                document.forms["formName"]

The second, even shorter way to reference a form object by name is to append the name as a property of the document object, as in document.formName
       

Document.Images[] Property

Just as a document keeps track of forms in an array property, so does the document object maintain a collection (array) of images inserted into the document by way of <img> tags.

Images referenced through the document.images array may be reached either by numeric or string index of the img element’s name. Just like forms, the name attribute value is the identifier you use for a string index.

The presence of the document.images property indicates that the browser supports image swapping. You can therefore use the existence of the property as a controller to make sure the browser supports images as objects before attempting to perform any script action on an image.

To do so, surround statements that deal with images with an if construction that verifies the property’s existence, as follows:

if (document.images)
{
// statements dealing with img objects
}


Document.Write[] Method

The document.write() method operates in both immediate scripts to create content in a page as it loads and in deferred scripts that create new content in the same or different window.

The method requires one string parameter, which is the HTML content to write to the window or frame.

Such string parameters can be variables or any other expressions that evaluate to a string. Very often, the written content includes HTML tags.

Bear in mind that after a page loads, the browser’s output stream automatically closes.

After that, any document.write() method issued to the current page opens a new stream that immediately erases the current page (along with any variables or other values in the original document). Therefore, if you wish to replace the current page with script-generated HTML, you need to accumulate that HTML in a variable and perform the writing with just one document.

Write() method. You don’t have to explicitly clear a document and open a new data stream; one document.write() call does it all.

One last advice about the document.write() method involves its companion method, document.close(). Your script must close the output stream when it finishes writing its content to the window (either the same window or another).

After the last document.write() method in a deferred script, be sure to include a document.close() method. Failure to do this may cause images and forms not to appear. Also, any document.write() method invoked later will only append to the page, rather than clear the existing content to write a new.

To demonstrate the document.write() method, I show two versions of the same application. One writes to the same document that contains the script; the other writes to a separate window.

Type in each document in a new text editor document, save it with an .html filename extension, and open it in your browser.

Example 1

Using document.write() on the Current Window

<html>
<head>
<title>Writing to Same Doc</title>
<script type="text/javascript">
function reWrite()
{
// assemble content for new window
var newContent = "<html><head><title>A New Doc</title></head>";
newContent += "<body bgcolor=’aqua’><h1>This document is brand new.</h1>";
newContent += "Click the Back button to see original document.";
newContent += "</body></html>";
// write HTML to new window document
document.write(newContent);
document.close(); // close layout stream
}
</script>
</head>
<body>
<form>
<input type="button" value="Replace Content"  onclick="reWrite()">
</form>
</body>
</html>

Explanation:

Creates a button that assembles new HTML content for a document, including HTML tags for a new document title and color attribute for the <BODY> tag.

An operator in the listing that may be unfamiliar to you is +=. It appends a string on its right side to whatever string is stored in the variable on its left side. This operator is a convenient way to accumulate a long string across several separate statements.

With the content gathered in the newContent variable, one document.write() statement blasts the entire new content to the same document, obliterating all vestiges of the content of old document.

The document.close() statement, however, is required to close the output stream properly. When you load this document and click the button, notice that the document title in the browser’s title bar changes accordingly.

As you click back to the original and try the button again, notice that the dynamically written second page loads much faster than even a reload of the original document.

Example 2

Using document.write() on Another Window

<html>
<head>
<title>Writing to Subwindow</title>
<script type="text/javascript">
var newWindow;
function makeNewWindow()
{
newWindow =window.open("","","status,height=200,width=300");
}

function subWrite()
{
// make new window if someone has closed it
if (newWindow.closed)
{
makeNewWindow();
}
// bring subwindow to front
newWindow.focus();
// assemble content for new window
var newContent = "<html><head><title>A New Doc</title></head>";
newContent += "<body bgcolor=’coral’><h1>This document is brand new.</h1>";
newContent += "</body></html>";


// write HTML to new window document
newWindow.document.write(newContent);
newWindow.document.close(); // close layout stream
}
</script>
</head>
<body onload="makeNewWindow()">
<form>
<input type="button"  value="Write to Subwindow" onclick="subWrite()">
</form>
</body>
</html>
 

In above example, the situation is a bit more complex because the script generates a subwindow to which is written an entirely script-generated document.

To keep the reference to the new window alive across both functions, the newWindow variable is declared as a global variable.

As soon as the page loads, the onload event handler invokes the makeNewWindow() function.

This function generates a blank subwindow. I added a property to the third parameter of the window.open() method that instructs the status bar of the subwindow to appear.

A button in the page invokes the subWrite() method. The first task it performs is to check the closed property of the subwindow.

This property (which exists only in newer browser versions) returns true if the referenced window is closed. If that’s the case (if the user manually closed the window), the function invokes the makeNewWindow() function again to reopen that window.

With the window open, new content is assembled as a string variable. The content is written in one blast (although that isn’t necessary for a separate window), followed by a close() method. But notice an important difference: both the write() and close() methods explicitly specify the subwindow.

Document.CreateElement() and Document.CreateTextNode() Methods
 

The document.write() method works on a piece of a Web page only while the page is loading into the browser the first time. Any subsequent invocation of the method erases the page and writes a new page. But if you want to add to or modify a page that has already loaded, you need to call upon the Dynamic HTML capabilities of W3C DOM-compatible browsers.

Your goal will be to add to, delete from, or replace sections of the node hierarchy of the document.

Most element objects have methods to perform those actions. But if you need to add content, you’ll have to create new element or text nodes.

The document object has the methods to do that.

The document.createElement() method lets you create in the browser’s memory a brand new element object. To specify the precise element you wish to create, pass the tag name of the element as a string parameter of the method:
                var newElem = document.createElement("p");

You may also wish to add some attribute values to the element, which you may do by assigning values to the newly created object’s properties, even before the element becomes part of the document.

Text content between its start and end tags. The W3C DOM way to create that text is to generate a brand new text node via the document.createTextNode() method, and populate the node with the desired text.
            For Example:
                var newText = document.createTextNode("Visions");

The act of creating an element or text node does not, by itself, influence the document node tree.

You must invoke one of the various insertion or replacement methods to place the new text node into its element and place the element into the document.

Document.getElementById() Method

The document.getElementById() method for referencing element objects. This W3C DOM method is one you will use a lot.

Be sure to honour the upper- and lowercase spelling of this all important method.

The sole parameter of this method is a quoted string containing the ID of the element you wish to reference. The method returns a value, which you typically preserve in a variable for use by subsequent script statements:

                Var oneTable = document.getElementById("Visions");