Understanding The Document Object In JavaScript

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 and 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 and the elements it displays which makes it possible for scripting languages like JavaScript to access and manipulate elements.

In the DOM, the HTML document is seen 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 also contains a cookie property which can be used to set and read cookies, small files which are stored on the user’s computer (with their permission) and 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”.

Another useful property of the document object is the domain property. This 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 and images properties of the document object. These are arrays containing all the forms and 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.

One other very useful property is the referrer property which 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.

Author is a developer and trainer with Macresource Computer Training, a UK IT training company offering JavaScript Classes in London and throughout the UK.

Leave a Reply