Home

JavaScript Tutorial

7. Using JavaScript Objects

When you load a document in your web browser, it creates a number of JavaScript objects with properties and capabilities based on the HTML in the document and other pertinent information. These objects exist in a hierarchy that reflects the structure of the HTML page itself.
The pre-defined objects that are most commonly used are the window and document objects. The window has methods that allow you to create new windows with the open() and close() methods. It also allows you to create message boxes using alert(), confirm(), and prompt(). Each displays the text that you put between the parentheses. For example, the following code:

alert("This is an alert box") ...pops up an alert box displaying the given message. Try it yourself by clicking on this link.
The document object models the HTML page. The document object contains arrays which store all the components constituting the contents of your web page, such as images, links, and forms. You can access and call methods on these elements of your web page through the arrays.
The objects in this pre-defined hierarchy can be accessed and modified. To refer to specific properties, you must specify the property name and all its ancestors, spelling out the complete hierarchy until the document object. A period, '.', is used in between each object and the name of its property. Generally, a property / object gets its name from the NAME attribute of the HTML tag. For example, the following refers to the value property of a text field named text1 in a form named myform in the current document.
document.myform.text1.value Form elements can also be accessed through the aforementioned forms array of the document object. In the above example, if the form named myform was the first form on the page, and text1 was the third field in the form, the following also refers to that field's value property.
document.forms[0].elements[2].value Functions (capabiltiies) of an object can similarly be accessed using the period notation. For example, the following instruction resets the 2nd form in the document.
document.forms[2].reset();

navigational tree