Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.
The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.
- Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.
- Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.
- Form object − Everything enclosed in the <form>…</form> tags sets the form object.
- Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes.
Methods of document object
We can access and change the contents of document by its methods.
The important methods of document object are as follows:
Method | Description |
---|---|
write(“string”) | writes the given string on the doucment. |
writeln(“string”) | writes the given string on the doucment with newline character at the end. |
getElementById() | returns the element having the given id value. |
getElementsByName() | returns all the elements having the given name value. |
getElementsByTagName() | returns all the elements having the given tag name. |
getElementsByClassName() | returns all the elements having the given class name. |
Accessing field value by document object
In this example, we are going to get the value of input text by user. Here, we are using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
Let’s see the simple example of document object that prints name with welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>