The JavaScript Document Object
In JavaScript a new document object is generated each time a page is loaded into a browser. Like all objects the document object exposes several methods & properties which can be accessed programmatically. One common document method is the write method which is used to output a text string to an HTML document. The document object forms part of the Document Object Model DOM a logical hierarchy representing an HTML page & the elements it displays which makes it possible for scripting languages like JavaScript to access & manipulate elements.
Within the DOM an HTML document is viewed as being composed of nodes arranged in a hierarchy each of which can be accessed in a number of ways. For example a node can be viewed as child or parent of another node or it could be referred to by its ID or its name. Since the document represents the entire HTML page many of its properties are actually collections of other objects. For example the anchors property is an array of all the named anchor objects on a page.
The document object has a cookie property which is used to set & read cookies small files which are stored on the user s computer with their permission & which can store information such as the user s preferences. When writing information the cookie property is set to a string representing the information; for example document.coookie = username=mikki .
The document object also has a domain property which automatically holds the domain name which contains the page currently being displayed in the browser. The value of document.domain can be read at any time to obtain this information.
Two examples of properties which are really collections are the forms & images properties of the document object. These are arrays containing all the forms & images on a page respectively. To count the number of forms or images on a page you can use the length property of these arrays document.forms.length or document.images.length. A length of zero would indicate that no forms/images are present on the page.
Another useful array is returned by the links property of the document; it contains all the hyperlinks on a page. Hyperlinks may be placed on text images or imagemap hotspots. As with other arrays you can use the length property to count the number of hyperlinks on a page.
The referrer property holds the value of the URL which the user was viewing prior to accessing the current page. This is only useful when the user has clicked a link to get to the page. If the user entered the URL directly into the browser address bar or used on of his or her bookmarks no value would be returned.
The writer of this article is developer & trainer with Macresource Computer Training: http://www.macresource.co.uk an independent computer training company offering JavaScript Classes: http://www.macresource.co.uk/courses/javascript.htm at their central London training centre.