Advanced Java and Web Technologies Tutorial
Beginner tutorials on different web technologies like HTML, CSS, Javascript, PHP, MYSQL, XML, Java Beans, Servlets, JSP and AJAX
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
AJWT » Javascript » Document Object Model
Suryateja Pericherla Categories: Javascript. No Comments on Document Object Model
Join Our Newsletter - Tips, Contests and Other Updates
Email
Name

Introduction

DHTML (Dynamic HTML) is not a new language. It is a combination of existing technologies like HTML, CSS, Javascript and DOM. Document Object Model (DOM) is a platform independent and language independent mechanism or API which allows the developer to implement dynamism into the web pages.

 

This article is a part of our advanced java and web technologies tutorial.

 

DOM represents the web page as a hierarchy of objects. The root object in the hierarchy is window. Using DOM, developers can add new elements, delete existing elements or modify the existing elements dynamically.

 

The DOM hierarchy is as shown below:

javascript Dom

 

Accessing Elements in a Document

Different elements in a web document are treated as objects in JavaScript and each object has properties and methods. Using DOM, we can get the address of an HTML element in different ways.

 

First way is to use the document object’s forms array property along with the elements array property. To understand this, let’s consider the following HTML code:

<html>
   <head><title>Simple form</title></head>
   <body>
      <form action="">
         Enter your name: <input type = "text" />
      </form>
   </body>
</html>

 

To obtain the address of the textbox in the above HTML code, you can write the following code in your script:

var  name = document.forms[0].elements[0].value;

 

The disadvantage of this method is, it becomes difficult to obtain the address of elements when there are multiple forms in a document or if there are a large number of elements in a form or if new elements are added to a form.

 

The second way is by using the name attribute of the HTML elements. To demonstrate this, let’s consider the following HTML code:

<html>
    <head><title>Simple form</title></head>
    <body>
       <form action="" name="frmmain">
          Enter your name: <input type = "text" name="txtname" />
       </form>
    </body>
</html>

 

To obtain the address of the textbox in the above HTML code, you can write the following code in your script:

var name = document.frmmain.txtname.value;

 

The problem with this method is, it doesn’t work with a group of checkboxes or a group of radio buttons which will have the same value for their name attribute. Also XHTML 1.1 does not allow name attribute on form tag.

 

The third way and the most commonly used method is by using the getElementById method which was introduced in DOM 1. To demonstrate this let’s consider the following HTML code:

<html>
   <head><title>Simple form</title></head>
   <body>
      <form action="">
         Enter your name: <input type = "text" id="txtname" />
      </form>
   </body>
</html>

 

To obtain the address of the textbox in the above HTML code, you can write the following code in your script:

var name = document.getElementById(“txtname”);

 

Since the value for id attribute can be different for checkboxes and radio buttons in a group, there will be no problems.

 

The id and name attributes can be used in combination for processing a group of checkboxes or radio buttons as shown below:

<form  id = "genderGroup">
   <input  type="radio"  name="gender"  value="male" />Male
   <input  type="radio"  name="gender"  value="female" />Female
</form>

 

var  count = 0;
var  dom = document.getElementById("genderGroup");
for(index = 0; index < dom.gender.length; index++)
    if(dom.gender[index].checked)
       count++;

 

Below listed are various objects available in the DOM and their properties and methods:

 

window object

Properties on window object are:

 

Property Description
closedIs a read-only Boolean property which returns true if the window opened using window.open() is closed and returns false otherwise
defaultStatusSpecifies the default message to be displayed on the window’s status bar when the webpage is loaded
nameA unique name used to reference the window
documentAn object that contains information about the webpage loaded in the window
historyAn object that contains the URLs visited by the user in the window
locationObject that contains information about the current URL
eventAn object that contains information about the event that occurred last. It is accessible only in the event handlers
framesThis is an array containing references to all frames in the window
lengthThe number of frames that the window contains
navigatorAn object that contains information about the browser application
screenRefers to the screen object associated with the window
screenLeft, screenTopSpecifies the x and y coordinates of the window, relative to the user’s monitor screen. These properties are specific to Internet Explorer
selfThis object is a synonym for the current window
topA reference to the top-level window in the object hierarchy
parentA reference to the parent window whose frameset contains the current frame
openerA reference to the window from which the current window was opened using the open() method
statusIt contains the message of the status bar of the window

 

Methods on window object are:

Method Description
alert(msg)Displays a dialog box with a specified message and an OK button
blur()Removes focus from this window
clearInterval(ID)Cancels a timeout that was set using the setInterval() method
clearTimeout(ID)Cancels a timeout that was set using the setTimeout() method
close()Closes this window
confirm(msg)Displays a dialog box with a specified message and OK and Cancel buttons
focus()Gives focus to this window
moveBy(dx, dy)Moves this window by the specified number of pixels
moveTo(x, y)Moves the top-left corner of the window to the specified screen coordinates
print()Prints the contents of the window or frame
open(URL, [name], [features], [replace])Opens a new browser window
prompt(msg, [input])Displays a dialog box with a message and an input field.
resizeBy(dx, dy)Resizes an entire window
resizeTo(x, y)Resizes an entire window to the specified outer height and width
scrollBy(dx, dy)Scrolls the viewing area of a window by the specified amount
scrollTo(x, y)Scrolls the viewing area of the window to the specified coordinates
setInterval(func, interval, [args])Executes a specified function every time a specified number of milliseconds elapses
setTimeout(func, interval, [args])Executes a specified function once after a specified number of milliseconds elapses
stop()Stops the current download

 

Features the can be applied in the open( ) method are:

Feature Name Description
toolbarWhether the toolbar should be present or not. Default is yes.
titlebarWhether the titlebar should be present or not. Default is yes.
statusStatus bar should be present or not. Default is yes.
scrollbarsWindow should have scrollbars or not. Default is yes.
resizableWindow can be resized or not. Default is yes.
menubarMenubar should be present or not. Default is yes.
locationWindow contains an address bar or not. Default is yes.
directoriesDirectory buttons should be present or not. Default is yes.
channelmodeShould be displayed in theater mode or not. Default is no.
fullscreenDisplay in full-screen mode or not. Default is no.

 

location object

Properties on location object are:

Property Description
hrefRefers the entire URL
hostnameURL host section
hostURL’s hostname and port section
portURL’s port section
pathnameURL’s pathname section
searchURL’s query string portion
protocolURL protocol name including “:”
hashURL anchor

 

Methods on location object are:

Method Description
reload()Current URL is reloaded. This is equal to refresh button on the browser. The argument true ignores browser cache and reloads
replace(URL)Loads the specified URL by replacing the current one. Does not affect the browser’s history

 

history object

Properties on history object are:

Property Description
currentCurrent webpage URL (Netscape only)
lengthNumber of entries of the history object
nextNext URL in the history object (Netscape only)
previousPrevious URL in the history object (Netscape only)

 

Methods on history object are:

Method Description
back()Loads previous URL in the history list
forward()Loads next URL in the history list
Go(relPos | string)Loads a specific URL in the history list. The relPos indicates number of places to go, relative to the current position. String argument indicates the specific URL to be loaded.

 

navigator object

Properties on navigator object are:

Property Description
appCodeCode name of the browser
appNameName of the browser
appMinorVersionMinor version number of the browser
cpuClassType of CPU
platformOS name
pluginsArray of plugins installed in the browser
systemLanguageLanguage being used by the system (en-us) (IE only)
userLanguageLanguage the user is using (en-us) (IE only)
appVersionVersion of the browser
userAgentInformation about the browser added in the HTTP header
onLineBoolean value of true or false
cookieEnabledSpecifies whether cookies are enabled or not
mimeTypesArray of MIME types supported by the browser (NS and firefox only)

 

Methods on navigator object are:

Method Description
javaEnabled()Indicates whether the browser supports javascript or not
taintEnabled()Indicates whether the browser supports taint (a security protection mechanism for data) or not

 

 

Next let’s learn about event handling in JavaScript.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram