16 JavaScript and HTML DOM
Dr M. Vijayalakshmi
Document Object Model or DOM
The DOM is a W3C (World Wide Web Consortium) standard. It defines a standard for accessing documents using a platform and language-neutral interface and to dynamically access and update the content, structure and style of a document.
The W3C DOM standard is separated into 3 different parts:
1. Core DOM – standard model for all document types
2. XML DOM – standard model for XML documents
3. HTML DOM – standard model for HTML documents
The Legacy DOM
This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements and images.
The W3C DOM
This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.
JavaScript – Document Object Model or DOM
The way a document content is accessed and modified is called the Document Object Model, or DOM. DOM is an object-oriented model that describes how all elements in an HTML page are arranged. It is used to locate any object in your HTML page (an unique address). Every web page resides inside a browser window which is considered as Window 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.
DOM – Objects
Here is a simple hierarchy of a few important objects shown in Figure 18.1.
HTML DOM
The HTML DOM is a standard object model and programming interface for HTML. DOM defines the HTML elements as objects, the properties of all HTML elements, the methods to access all HTML elements, the events for all HTML elements. The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
JavaScript – HTML DOM Programming Interface
- The HTML DOM can be accessed with JavaScript and with other programming languages.
- In the DOM, all HTML elements are defined as objects.The programming interface defines the properties and methods of each object.
- Methods are actions you can perform on HTML Elements.
- Properties are values of HTML Elements that you can set or change.
Referencing Objects
Objects can be referenced using their id or name. It should be unique in the hierarchy. It can be referenced using their numerical position in the hierarchy, by the array index. They can also be referenced using their relation to parent, child, or sibling like parentNode, previousSibling, nextSibling, firstChild, lastChild or the childNodes array.
Types of DOM nodes
1 | Element nodes | HTML tag |
2 | Text nodes | text in a block element |
3 | Attribute nodes | attribute/value pair |
Element nodes can have children and/or attributes. Text or Attribute nodes are children in an element node. They cannot have children or attributes and not usually shown when drawing the DOM tree
Traversing the DOM tree
The nodes in the DOM tree can be traversed using the relationship like firstChild, lastChild, childNodes, nextSibling, previousSibling and parentNode. The description of these relationships are given in the below Table 18.1.
Table 18.1 Relationships among Nodes
Accessing HTML Elements
All HTML elements (objects) are accessed through the document object. A document itself is automatically created. There are several ways to access a specific element, either using paths in the DOM tree or retrieval by tag or retrieval by ID.
Methods in document and other DOM objects for accessing descendants
There are two methods in Document object and other DOM objects for accessing the elements. They are,
getElementsByTagName
getElementsByName
Accessing Elements by Paths
Example
function execute()
{
var img = document.images[0]; img.src=”lighton.gif”
var inx = document.forms[0].elements[0]; inx.value=”xx”
var iny = document.forms[“form1”].elements[“y”]; iny.value=”yy”
}
<p><img src=”lightoff.gif” alt=”light off” id=”img1″ /></p> <form id=”form1″ method=”get” action=”nosuch”><p>
<input type=”text” name=”x”/>
<input type=”text” name=”y”/>
<input type=”reset”/></p>
</form>
Accessing Elements by Tags
Example
function execute()
{
var spans = document.getElementsByTagName(“span”);
spans[0].style.color=”red”;
spans[1].style.color=”blue”;
Spans[1].style.fontVariant=”small-caps”;
}
<p> This <span>example</span> is lovely. </p> <p> But <span> this one </span>is even more! </p>
Accessing Elements by ID
Example
function execute() {
var theDiv = document.getElementById(“div1″);
if (theDiv.style.visibility==”hidden” )
{ theDiv.style.visibility=”visible” } else { theDiv.style.visibility=”hidden” }
}
<div id = “div1”> This text can be hidden! </div>
HTML DOM – Example
Example:
To change the content ( i.e., the innerHTML) of the <p> element with id = “demo“.
<html>
<body>
<p id=”demo”></p>
<script>
document.getElementById(“demo”).innerHTML = “Hello World!”;
</script>
</body>
</html>
getElementById is a method and innerHTML is a property.
The “window” Object
It is the highest-level object in the JavaScript browser object hierarchy. It is the default object and is created automatically when a page is loaded. Since it is the default object, we may omit writing window explicitly.
Hence we use the method
document.write(“a test message”)
instead of
window.document.write(“a test message”);
It also includes several properties and methods for us to manipulate the webpage.
“window” Object – Property
Some of the properties of the window object is listed in Table 18.2.
“window” Object – Method
Some of the methods of the window object is listed in Table 18.3.
“window” Object – Attribute
Some of the attributes of the window object is listed in Table 18.4.
Window object example
<html>
<head>
<script>
var w;
function openwindow()
{
w = window.open(”,”, ‘width=100,height=100’);
w.focus();
}
function myFunction()
{
w.resizeBy(50, 50);
w.focus();
}
</script>
</head>
<body>
<button onclick=”openwindow()”>Create window</button> <button onclick=”myFunction()”>Resize window</button> </body>
</html>
This example shows the use of window object. The example shows the open(), resize() and focus() method of the window object. There are two buttons, “Create Window” and “Resize window”. On clicking these buttons, it invokes the open() method or resize() method. Once the window is resized, in order to gain focus on the window, focus() method is also used with the window object as shown in Figure 18.2
The “document” Object
It is one of the important objects in any window or frame. The document object represents a web document or a page in a browser window.
“document” Object – Property
Some of the properties of the document object is listed in Table 18.5.
Table 18.5 “document” Object – Property
“document” Object – Method
Some of the methods of the document object is listed in Table 18.6.
Document Object Example
<html>
<body>
<script>
document.write(“Hello World!”);
</script>
<p>Click the button to display the number of script elements in the document.</p> <button onclick=”myFunction()”>Try it</button>
<p id=”demo”></p>
<script>
function myFunction() {
var x = document.scripts.length;
document.getElementById(“demo”).innerHTML = “Found ” + x + ” script elements.”;
}
</script>
</body>
</html>
This example demonstrates how document object can be used. The write() method can be used with the document object to display output text “Hello World!”. On clicking the button, the number of scripts found in the document can be displayed using the property “length” of the object as shown in Figure 18.3.
<html>
<body>
<p>Click the button to display the URL of the document.</p> <button onclick=”myFunction()”>Try it</button> <p id=”demo”></p>
<script>
function myFunction()
{
var x = document.URL;
document.getElementById(“demo”).innerHTML = x;
}
</script></body>
</html>
Figure 18.4 displays the URL of the document. The example shows the use of the property “URL” used with the document object.
The “history” Object
Each time you visit a web page and click on the “Back” or “Forward” arrow buttons on your browser toolbar, you are accessing the history list. You can also add similar buttons / links that allow users to move backward and forward via the information stored in the history object.
“history” Object – Property
Some of the properties of the history object is listed in Table 18.7.
“history” Object – Method
Some of the methods of the history object is listed in Table 18.8.
History Object Example
<html>
<body>
<p>Display the number of URLs in the history list:</p> <button onclick=”myFunction()”>Try it</button>
<p id=”demo”></p>
<script>
function myFunction()
{
document.getElementById(“demo”).innerHTML = history.length;
}
</script>
</body>
</html>
Figure 18.5 shows the property length of the history object. It displays the number of URL’s in the history list.
History Object Example
<html>
<head>
<script>
function goBack()
{
window.history.go(-2)
}
</script>
</head>
<body>
<button onclick=”goBack()”>Go 2 pages back</button> </body>
</html>
This example uses the method go() of the “history” object. Figure 18.6 displays the button “Go 2 pages back”. On clicking the button, it calls the function goBack() which navigates two pages back and hence the output shown as the Google home page shown in Figure 18.7.
Anchor Object – Example
<html>
<body>
<p> <a id=”myAnchor”
href=”http://www.example.com:4097/test.htm#part2″>Exam ple link </a></p> <p>Click the button to display the port num ber of the link above.</p> <button onclick=”myFunction()”>Try it</button>
<p id=”demo”></p>
<script>
function myFunction() {
var x = document.getElementById(“myAnchor”).port; document.getElementById(“demo”).innerHTML = x;
}
</script>
</ body>
</ html>
This example shows the property “port” used with the Anchor object. The property retrieves the port number of the anchor given as link and displays it as shown in Figure 18.8.
The “form” Object
The form object is accessed as a property of the document object. Each form element in a form (text input field, radio buttons), is further defined by other objects. The browser creates a unique “form” object for each form in a document. You can access the form object “form1” using the path document.form1.
Form Element-Based Objects
HTML forms can include eight types of input elements
a. Text fields, Textarea fields
b. Radio buttons
c. Check box buttons
d. Hidden fields
e. Password fields
f. Combo box select menu
g. List select menu
Working with DOM
Example:
<html>
<body>
<img border=”0″ src=”grapes.jpg” width=”48″ height=”48″>< br> <img border=”0″ src=”flower.jpg” width=”107″ height=”98″><br> <img border=”0″ src=”fish.jpg” width=”107″ height=”98″><br> <p>
<script type=”text/javascript”> document.write(“<hr><b>This document contains: ”
+ document.images.length + ” images.</b>”) </script>
</p>
</body>
</html>
This example demonstrate the property length used with the image object. Figure 18.9 displays the number of images found in the document object.
Working with DOM – Output
Summary
This module is discussed about HTML DOM object hierarchy and explains about how to access HTML elements using DOM. This module also explores about working with DOM objects using JavaScript.
Web Links
- www.doc.ic.ac.uk/~rcheung/teaching/2720/ppt/lecture04c.ppt
- www.cs.huji.ac.il/~dbi/lectures/dhtml/dhtml.ppt