Lecture 15
Document Object Model
The DOM defines a standard for accessing and manipulating
HTML documents.
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can create new HTML events in the page
See: http://www.w3schools.com/js/js_htmldom.asp/
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing and manipulating
HTML documents.
A representation of the current web page as a tree of JavaScript objects
Allows you to view/modify page elements in script code
The DOM defines the objects and properties of all document
elements, and the methods (interface) to access them.
According to the DOM, everything in an HTML document is a
node.
The DOM says:
The entire document is a document node
Every HTML element is an element node
The text in the HTML elements are text nodes
Every HTML attribute is an attribute node
Comments are comment nodes
Consider Following Code:
<html>
<head>
<title>My title</title>
</head>
<body>
<h1>My header</h1>
<a href="http://fc.riphah.edu.pk">My link</a>
</body>
</html>
The nodes in the node tree have a hierarchical
relationship to each other
In a node tree, the top node is called the root
Every node, except the root, has exactly one parent node
A node can have any number of children
A leaf is a node with no children
Siblings are nodes with the same parent
Some DOM properties:
x=document.getElementById(“intro”);
x.innerHTML - the text value of x
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x
Note: In the list above, x is a node object (HTML element).
The nodeName Property (x.nodeName)
nodeName is read-only
nodeName of an element node is the same as the tag name
nodeName of an attribute node is the attribute name
nodeName of a text node is always #text
nodeName of the document node is always #document
The nodeValue Property (x.nodeValue)
nodeValue for element nodes is undefined
nodeValue for text nodes is the text itself
nodeValue for attribute nodes is the attribute value
Some DOM methods:
x.getElementById(id) - get the element with a specified id
x.getElementsByTagName(name) - get all elements with a specified tag
name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x
You can access a node in three ways:
By using the getElementById() method
By using the getElementsByTagName() method
By navigating the node tree, using the node relationships
There are two special document properties that allow access to the tags:
document.documentElement - returns the root node of the document
document.body - gives direct access to the <body> tag
<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementById</b> method!</p>
<script>
x=document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " +
x.innerHTML + "</p>");
</script>
See: Example 01
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<script>
x=document.getElementsByTagName("p");
document.write("Text of second paragraph: " + x[1].innerHTML);
</script>
See: Example 02
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>length</b> property.</p>
<script>
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
</script>
See: Example 03
document.getElementById("p1").innerHTML="New text!";
Syntax:
document.{HTML-Element}.style.{property}=“Value”;
Examples:
document.body.style.backgroundColor="#cccccc";
document.getElementById("p1").style.color="#00cc00";
document.getElementById("p1").style.fontFamily="Arial";
See: http://www.w3schools.com/jsref/dom_obj_style.asp
Every JavaScript program can refer to the following global
objects:
window : the browser window
navigator : info about the web browser you're using
screen : info about the screen area occupied by the browser
history : list of pages the user has visited
location : URL of the current HTML page
document : current HTML page object model
The window object represents an open window in a browser.
The top-level object in the DOM hierarchy
Technically, all global variables become part of the window object
Methods:
alert, blur, clearInterval, clearTimeout, close, open, confirm, focus, moveBy,
moveTo, print, prompt, resizeBy, resizeTo, scrollBy, scrollTo, setInterval,
setTimeout
Properties:
document, history, location, name
See: http://www.w3schools.com/jsref/obj_window.asp
function delayedMessage() {
var myTimer = setTimeout("alert('Booyah!');", 5000);
}
<h2 onclick="delayedMessage();">Click me now!</h2>
setTimeout executes a piece of code once after a given number of
milliseconds
the function returns an object representing the timer
to cancel the timer, call clearTimeout and pass the timer object
clearTimeout(myTimer); // cancel self-destruct sequence!
See: Example 04
<input type="text" id="clock" />
<script type="text/javascript">
var myTimer=setInterval("clock()",1000);
function clock()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("clock").value=t;
}
</script>
<button
onclick="window.clearInterval(myTimer)">Stop</button>
See: Example 05
Information about the web browser application
Methods:
javaEnabled()
Properties:
appCodeName, appName, appVersion, ,cookieEnabled, geolocation,
language, onLine, platform, product , userAgent
See: http://www.w3schools.com/jsref/obj_navigator.asp
<div id="example"></div>
<script type="text/javascript">
<!--
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
Txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Language: " + navigator.language + "</p>";
txt+= "<p>Online: " + navigator.onLine + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>Product: " + navigator.product + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
//-->
</script>
See: Example 06
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this
browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
See: Example 10 Example 11
Information about the client's display screen
Properties:
availHeight, availWidth, colorDepth, height, pixelDepth, width
See: http://www.w3schools.com/jsref/obj_screen.asp
document.write("Total width/height: ");
document.write(screen.width + "*" + screen.height);
document.write("<br />");
document.write("Available width/height: ");
document.write(screen.availWidth + "*" + screen.availHeight);
document.write("<br />");
document.write("Color depth: ");
document.write(screen.colorDepth);
document.write("<br />");
document.write("Color resolution: ");
document.write(screen.pixelDepth);
See: Example 07
List of sites the browser has visited in this window
Properties:
length
Methods:
back, forward, go
See: http://www.w3schools.com/jsref/obj_history.asp
<script type="text/javascript">
function goBack()
{
window.history.back()
}
</script>
<input type="button" value="Back" onclick="goBack()" />
See: Example 08
Represents the URL of the current web page
Properties:
host, hostname, href, pathname, port, protocol, search
Methods:
assign, reload, replace
See: http://www.w3schools.com/jsref/obj_location.asp
<script type="text/javascript">
function newDoc()
{
window.location.assign("http://www.w3schools.com")
}
</script>
<input type="button" value="Load new document"
onclick="newDoc()" />
See: Example 09
Represents current HTML page object model
Properties:
anchors, body, cookie, domain, forms, images, links, referrer, title, URL
Methods:
getElementById, getElementsByName, getElementsByTagName, write,
writeln
See: http://www.w3schools.com/jsref/dom_obj_document.asp
JavaScript can be used to validate data in HTML forms
before sending off the content to a server.
Form data that typically are checked by a JavaScript could
be:
Required Field
Valid Email Address
Numeric Field
<script type="text/javascript">
function validateForm()
{
...
}
</script>
<form name="myForm" action="somescript.php"
onsubmit="return validateForm()" method="post">
...
<input type="submit" value="Submit">
</form>
function validateForm() {
var formErrors="";
var x;
x=document.forms["myForm"]["fullname"].value;
if (x==null || x=="") {
formErrors=formErrors+"Name Required \n";
}
if (formErrors!="") {
alert(formErrors);
return false;
}
}
See: Example 03
A cookie is a variable that is stored on the visitor's computer.
Each time the same computer requests a page with a browser, it will send
the cookie too.
With JavaScript, you can both create and retrieve cookie values.
A cookie is nothing but a small text file that's stored in your browser. It
contains some data:
A name-value pair containing the actual data
An expiry date after which it is no longer valid
The domain and path of the server it should be sent to
Cookies can be created, read and erased by JavaScript. They are accessible
through the property document.cookie.
document.cookie = "wpone=test; expires=Tue, 31 Dec
2013 23:59:59 UTC; path=/";
1. First the name-value pair (wpcookie=test)
2. then a semicolon and a space
3. then the expiry date in the correct format (expires=Tue, 31 Dec
2013 23:59:59 UTC)
4. again a semicolon and a space
5. then the path (path=/)
document.cookie = "wpone=test; expires=Tue, 31 Dec
2014 23:59:59 UTC; path=/";
document.cookie = "wptwo=another test; expires=Tue,
31 Dec 2014 23:59:59 UTC; path=/";
The second one is added to document.cookie, so if we read it out we get
document.write(document.cookie);
wpone=test; wptwo=another test
See: Example 01
function setCookie(name, value, days) {
var expDate = new Date();
var expTime = expDate.getTime() + (days*24*60*60*1000);
expDate.setTime(expTime);
var expires = "; expires="+expDate.toUTCString();
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var cname = name + "=";
var carray = document.cookie.split(';');
for(var i=0;i < carray.length;i++) {
var c = carray[i];
while (c.charAt(0)==' ')
c = c.substring(1,c.length);
if (c.indexOf(cname) == 0)
return c.substring(cname.length,c.length);
}
return null;
}
See: Example 02
Q&A