You are on page 1of 75

WEB PROGRAMMING

SUBJECT CODE : TCA8C33


YEAR I .M COM (CA ) 2010-2012

1.
2.
3.
4.
5.

Unit 1 :
Unit II :
Unit III :
Unit IV :
Unit V :

Introduction HTML
More on HTML , HTML CSS
Introduction to java Script Object in Java Script
Dynamic HTML with JAVASCRIPT
XML Defining Data for web Applications

Text :1. Web Programming Building Internet Appliation Chiris Bates Second Edition
Wiley & Sons 2002 Chapter 1-7, 14

John

Ref : 1. Web enabled commercial application development using HTML ,DHTML JAvascript
,Perl ,CGI Ivan Bayross BPB Publications First edition 2000
2. Web design david crowder Rhonda Crowder IDG Books India First Edition 2001

UNIT 1: Hyper Text Markup Language


Origins of HTML

Tim Berners-Lee
In 1980, physicist Tim Berners-Lee, who was a contractor at CERN, system for CERN researchers to use
and share documents. In 1989, Berners-Lee wrote a memo proposing an Internet-based hypertext
system.[2] Berners-Lee specified HTML and wrote the browser and server software in the last part of
1990. "some of the many areas in which hypertext is used" and puts an encyclopedia first.Hypertext
Ability to link to other documents, especially using URLs Mark-up Uses Tags to tell a browser how to
display text, images, links etc. URL -Uniform Resource Locator
Program:1
<HTML>
<HEAD>
<TITLE>Tags</TITLE>
</HEAD>
<BODY>
<IMG SRC="flag.gif">
<H1>Sample web page</H1><B>This text is bold, <I>this is bold + italics</I></B>
<BR>This is plain with lots of embedded spaces
<P>This is a new paragraph</P>
<P>and so is this</P>
Click <A HREF="http://www.hud.ac.uk/"> here </A>for University web page
</body> <html >

es
ks
ges
les
s
ms
mes
mes
ors
o
o
c

v
t

d
a
pts
ties
Ls
L
bs
mm

2. ELEMENTS OF HTML
HTML documents are defined by HTML elements.
HTML Element Syntax
An HTML element starts with a start tag / opening tag
An HTML element ends with an end tag / closing tag
The element content is everything between the start and the end tag
Some HTML elements have empty content
Empty elements are closed in the start tag
Most HTML elements can have attributes

HTML Elements
An HTML element is everything from the start tag to the end tag:
Start tag *
<p>
<a href= default.html>
</br>

Element content
This is a paragraph
This is a link

End tag *
</p>
</a>

* The start tag is often called the opening tag. The end tag is often called the closing tag.
HTML Attributes
HTML elements can have attributes
Attributes provide additional information about an element
Attributes are always specified in the start tag
Attributes come in name/value pairs like: name="value"

Attribute Example : Program 2


HTML links are defined with the <a> tag. The link address is specified in the href attribute:
<a href="http://www.w3schools.com">This is a link</a>

am
m
z
if

er
L
3

ib
nts
or
or
ra
CII

LE
g
us

Ordered Alphabetically
DTD: indicates in which HTML 4.01 / XHTML 1.0 DTD the tag is allowed. S=Strict, T=Transitional, and
F=Frameset
Tag
<!--...-->
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area />
<b>
<base />
<basefont />
<bdo>
<big>
<blockquote>
<body>
<br />
<button>
<caption>
<center>
<cite>
<code>
<col />
<colgroup>
<dd>
<del>
<dfn>
<dir>

Description
Defines a comment
Defines the document type
Defines an anchor
Defines an abbreviation
Defines an acronym
Defines contact information for the author/owner of a document
Deprecated. Defines an embedded applet
Defines an area inside an image-map
Defines bold text
Defines a default address or a default target for all links on a page
Deprecated. Defines a default font, color, or size for the text in a page
Defines the text direction
Defines big text
Defines a long quotation
Defines the document's body
Defines a single line break
Defines a push button
Defines a table caption
Deprecated. Defines centered text
Defines a citation
Defines computer code text
Defines attribute values for one or more columns in a table
Defines a group of columns in a table for formatting
Defines a description of a term in a definition list
Defines deleted text
Defines a definition term
Deprecated. Defines a directory list

DTD
STF
STF
STF
STF
STF
STF
TF
STF
STF
STF
TF
STF
STF
STF
STF
STF
STF
STF
TF
STF
STF
STF
STF
STF
STF
STF
TF
4

<div>
<dl>
<dt>
<em>
<fieldset>
<font>
<form>
<frame />
<frameset>
<h1> to <h6>
<head>
<hr />
<html>
<i>
<iframe>
<img />
<input />
<ins>
<isindex>
<kbd>
<label>
<legend>
<li>
<link />
<map>
<menu>
<meta />
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<p>
<param />
<pre>
<q>
<s>
<samp>

Defines a section in a document


Defines a definition list
Defines a term (an item) in a definition list
Defines emphasized text
Defines a border around elements in a form
Deprecated. Defines font, color, and size for text
Defines an HTML form for user input
Defines a window (a frame) in a frameset
Defines a set of frames
Defines HTML headings
Defines information about the document
Defines a horizontal line
Defines an HTML document
Defines italic text
Defines an inline frame
Defines an image
Defines an input control
Defines inserted text
Deprecated. Defines a searchable index related to a document
Defines keyboard text
Defines a label for an input element
Defines a caption for a fieldset element
Defines a list item
Defines the relationship between a document and an external resource
Defines an image-map
Deprecated. Defines a menu list
Defines metadata about an HTML document
Defines an alternate content for users that do not support frames
Defines an alternate content for users that do not support client-side scripts
Defines an embedded object
Defines an ordered list
Defines a group of related options in a select list
Defines an option in a select list
Defines a paragraph
Defines a parameter for an object
Defines preformatted text
Defines a short quotation
Deprecated. Defines strikethrough text
Defines sample computer code

STF
STF
STF
STF
STF
TF
STF
F
F
STF
STF
STF
STF
STF
TF
STF
STF
STF
TF
STF
STF
STF
STF
STF
STF
TF
STF
TF
STF
STF
STF
STF
STF
STF
STF
STF
STF
TF
STF
5

<script>
<select>
<small>
<span>
<strike>
<strong>
<style>
<sub>
<sup>
<table>
<tbody>
<td>
<textarea>
<tfoot>
<th>
<thead>
<title>
<tr>
<tt>
<u>
<ul>
<var>
<xmp>

Defines a client-side script


Defines a select list (drop-down list)
Defines small text
Defines a section in a document
Deprecated. Defines strikethrough text
Defines strong text
Defines style information for a document
Defines subscripted text
Defines superscripted text
Defines a table
Groups the body content in a table
Defines a cell in a table
Defines a multi-line text input control
Groups the footer content in a table
Defines a header cell in a table
Groups the header content in a table
Defines the title of a document
Defines a row in a table
Defines teletype text
Deprecated. Defines underlined text
Defines an unordered list
Defines a variable part of a text
Deprecated. Defines preformatted text

STF
STF
STF
STF
TF
STF
STF
STF
STF
STF
STF
STF
STF
STF
STF
STF
STF
STF
STF
TF
STF
STF

Headings are important in HTML documents.


HTML Headings
Headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important heading.

EXAMPLE No 3 : HEADING TAGS

Program 4 : HTML TEXT FORMATTING TAGS:

TABLE
HTML Tables
Tables are defined with the <table> tag.
A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td>
tag). td stands for "table data," and holds the content of a data cell. A <td> tag can contain text, links,
images, lists, forms, other tables, etc.
Table Headers
Header information in a table are defined with the <th> tag.
All major browsers will display the text in the <th> element as bold and centered.

HTML Table Tags


Tag

Description

<table>

Defines a table

<th>

Defines a table header

<tr>

Defines a table row

<td>

Defines a table cell

<caption>

Defines a table caption

<colgroup>

Defines a group of columns in a table, for formatting

<col />

Defines attribute values for one or more columns in a table

<thead>

Groups the header content in a table

<tbody>

Groups the body content in a table

<tfoot>

Groups the footer content in a table

Program no: 9

cell padding to create more white space between the cell content and its borders.
Cell spacing cell spacing to increase the distance between the cells.

Program No 7 : HTML LINKS:

Program 8: HTML IMAGES:

10

HTML Forms
HTML forms are used to pass data to a server.
A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A
form can also contain select lists, textarea, fieldset, legend, and label elements.
The <form> tag is used to create an HTML form:
<form>
.
input elements
.
</form>
Program No: 10 Text Fields
<input type="text" /> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
</form>
How the HTML code above looks in a browser:
First name:
Last name:
Note: The form itself is not visible. Also note that the default width of a text field is 20 characters.

Password Field
<input type="password" /> defines a password field:
<form>
Password: <input type="password" name="pwd" />
</form>
FRAMES:
HTML Frames
11

With frames, you can display more than one HTML document in the same browser window. Each HTML
document is called a frame, and each frame is independent of the others.
The disadvantages of using frames are:
Frames are not expected to be supported in future versions of HTML
Frames are difficult to use. (Printing the entire page is difficult).
The web developer must keep track of more HTML documents
The HTML frameset Element
The frameset element holds one or more frame elements. Each frame element can hold a separate
document.
The frameset element states HOW MANY columns or rows there will be in the frameset, and
HOW MUCH percentage/pixels of space will occupy each of them.
The HTML frame Element
The <frame> tag defines one particular window (frame) within a frameset.
In the example below we have a frameset with two columns.
The first column is set to 25% of the width of the browser window. The second column is set to
75% of the width of the browser window. The document "frame_a.htm" is put into the first
column, and the document "frame_b.htm" is put into the second column:

Program No 11 : FRAMES
<html>
<title> Frames</title>
<body>
<frameset cols="25%,75%">
<frame src="frame_a.htm" />
<frame src="frame_b.htm" />
</frameset>
</body>
</html>
Note: The frameset column size can also be set in pixels (cols="200,500"), and one of the
columns can be set to use the remaining space, with an asterisk (cols="25%,*").
12

Program No 12: For TWO FRAMES

13

UNIT II :

Styling HTML with CSS

CSS was introduced with HTML 4, to provide a common way to style HTML elements.
What is CSS?
CSS stands for Cascading Style Sheets
Styles define how to display HTML elements
Styles were added to HTML 4.0 to solve a problem
External Style Sheets can save a lot of work
External Style Sheets are stored in CSS files
CSS styling can be added to HTML in the following ways
in separate style sheet files (CSS files)
in the style element in the HTML head section
in the style attribute in single HTML elements.
Style sheets contain rules composed of selectors and declarations that defines how styles will be
applied. The selector a redefined HTML elements class name or ID names is the link between the
html document and the style There are two different kinds of selectors types (HTML document
and tags ) and attributes such as (class and ID names )
Advantages of CSS:
CSS saves time: When most of us forst learn HTML we are taught to set the font face size
color sytle etc., everytimes it occurs on a page CSS will automatically apply the specified styles
wheneven that element occurs
Page Load Faster:

Less code means faster download times.

Easy maintanances: To change the style of an element you only have to make an edit in one
place .
Superior Styles to HTML: CSS has a much wider array of attributes than HTML.
Disadvantages of CSS:
Browser Compatibility: The two main browsers (Ntscape and internet Explorer) have varying
levels of compliance with style sheets this means that some style sheet features are supported and
some are not

14

CSS Triangle Arrow DIVs


Author: Dynamic Drive
An subtle characteristic of CSS that's been exploited to do something interesting is CSS borders and using
it to create pure CSS triangles. These triangles have the advantage of being extremely lightweight (no
image used) and scalable to boot. The technique works using the fact that the 4 CSS borders of an element
meet at an angle; when the dimensions of the element is set to 0, the 4 borders collapse and touch one
another, creating the appearance of 4 triangles:

Here's the CSS used to create the above DIV:


Style:
#triangles{
margin:3em;
width:0; /*set dimensions of DIV to 0 so its borders collapse and touch one
another*/
height:0;
border-color: red blue green yellow; /*top, right, bottom, and left border*/
border-style: solid;
border-width: 50px; /*width of each border*/
}
Markup:
<div id="triangles"></div>
To display just a specific triangle then, you would set the border-color of all but the desired border side to
transparent.
The following adds a CSS based triangle to a DIV to produce a speech bubble look that can be used to
show comments, quotes etc. Each arrow is added to the DIV with no markup used by way of CSS
15

Generated Content. The result are regular DIVs injected with progressive CSS enhancements that degrade
well in less capable browsers.

16

<div class="uparrowdiv">
This is a test </div>
<div class="downarrowdiv">
This is a test </div>
17

<div class="leftarrowdiv">
This is a test </div>

<div class="rightarrowdiv">
This is a test </div>

DYNAMIC CSS STYLES:


Since a large part of DHTML has to do with changing style settings of XHTML elements, it will be
helpful to review the application of Cascading Style Sheets (CSS) to page elements. Although most CSS
settings are not intended for dynamic change, any and all such settings are available for change at the
discretion of the page designer.
Inline Style Sheets
Style sheets are applied to XHTML elements in three ways. Inline style sheets are applied by coding style
properties and values inside the tags to which they apply.
<tag style="property:value [; property:value]...">
Figure 1-30. General format for inline style sheet.
The keyword style is followed by a quoted list of style properties and associated values, connected with
colons (:) and separated by semicolons (;). For instance, to set the font family and font size for the text
contained within a paragraph, the following inline style sheet is coded inside the opening <p> tag.
<p style="font-family:arial; font-size:9pt">
This is a paragraph styled with an inline style sheet.
</p>
Listing 1-15. Setting inline styles for a paragraph.
An inline style sheet can appear inside any tag to directly set its style. All that is required is to enclose the
applicable style properties and values inside a quoted style attribute.
Embedded Style Sheets
When a large number of style settings are used on a Web page, there is convenience in packaging the
settings together in one place as an embedded style sheet, rather than having them scattered as inline
style sheets throughout the document. An embedded style sheet normally is coded inside the <head>
section of the document surrounded by a <style> tag. It applies styles across the entire Web page through
18

simple selectors, ID selectors, group selectors, contextual selectors, and class selectors, whose general
formats are shown in Figure 1-31 and discussed below.
<style type="text/css">
tag
{property:value [; property:value]...}
tag#id
{property:value [; property:value]...}
tag, tag, ... {property:value [; property:value]...}
tag tag ... {property:value [; property:value]...}
.class
{property:value [; property:value]...}
</style>
Figure 1-31. General formats for embedded style sheet settings.
Simple Selectors
When associating styles with a particular type of tag, the tag name is followed by a set of properties and
values enclosed within braces { }. For instance, to set the font family and size for all paragraphs in a
document, the following simple selector entry is coded.
p {font-family:arial; font-size:9pt}
Listing 1-16. Using a simple selector to style a <p> tag.
Now, wherever a <p> tag is encountered in the Web document, the browser applies these styles to its
content.
Group Selectors
In a similar manner, identical styles can be applied to multiple tags by listing the tag names separated by
commas. In the following example, all <h1>, <h2>, and <h3> tags appearing on a page receive the same
styling.
h1, h2, h3 {font-family:arial; color:blue}
Listing 1-17. Using group selectors to style multiple heading tags.

Program 1:
Using the HTML Style Attribute
It is time consuming and not very practical to style HTML elements using the style attribute.
HTML Style Example - Background Color
19

The background-color property defines the background color for an element:

Program 2:

Unit 3: Introduction to JavaScript


JavaScript is a programming language that can be included on web pages to make them
more interactive. We can use it to check or modify the contents of forms, change images, open
new windows and write dynamic page content. We can even use it with CSS to make DHTML
(Dynamic HyperText Markup Language). This allows you to make parts of your web pages
20

appear or disappear or move around on the page. JavaScripts only execute on the page(s) that are
on your browser window at any set time. When the user stops viewing that page, any scripts that
were running on it are immediately stopped. The only exception is a cookie, which can be used
by many pages to pass information between them, even after the pages have been closed.
JavaScript is a client side, interpreted, object oriented, high level scripting language,
while Java is a client side, compiled, object oriented high level language. Now after that
mouthful, here's what it means.
Client side
Programs are passed to the computer that the browser is on, and that computer runs them. The
alternative is server side, where the program is run on the server and the results are passed to the
computer that the browser is on. Examples of this would be PHP, Perl, ASP, JSP etc.
Interpreted
The program is passed as source code with all the programming language visible. It is then
converted into machine code as it is being used. Compiled languages are converted into machine code
first then passed around, so you never get to see the original programming language. Java is actually dual
half compiled, meaning it is half compiled (to 'byte code') before it is passed, then executed in a virtual
machine which converts it to fully compiled code just before use, in order to execute it on the computer's
processor. Interpreted languages are generally less fussy about syntax and if you have made mistakes in a
part they never use, the mistake usually will not cause you any problems.
Scripting
They may be complete programming languages, they do not usually go into the depths of
complex programs, such as thread and memory management. They may use another program to do the
work and simply tell it what to do. They often do not create their own user interfaces, and instead will
rely on the other programs to create an interface for them. This is quite accurate for JavaScript. We do not
have to tell the browser exactly what to put on the screen for every pixel (though there is a relatively
new API known as canvas that makes this possible if needed), we just tell it that we want it to change the
document, and it does it. The browser will also take care of the memory management and thread
management, leaving JavaScript free to get on with the things it wants to do.

High level
Written in words that are as close to english as possible. The contrast would be with assembly
code, where each command can be directly translated into machine code.
Object oriented
See the section on 'object oriented programming' for details.
How is JavaScript constructed
The basic part of a script is a variable, literal or object.
21

A variable is a word that represents a piece of text, a number, a boolean true or false
value or an object.
A literal is the actual number or piece of text or boolean value that the variable
represents.
An object is a collection of variables held together by a parent variable, or a
document component and
The next most important part of a script is an operator. Operators assign literal values
to variables or say what type of tests to perform.
The next most important part of a script is a control structure. Control structures say what
scripts should be run if a test is satisfied.
Functions collect control structures, actions and assignments together and can be told to
run those pieces of script as and when necessary.
The most obvious parts of a script are the actions it performs. Some of these are done with
operators but most are done using methods. Methods are a special kind of function and may do things like
submitting forms, writing pages or displaying messages.
Events can be used to detect actions, usually created by the user, such as moving or clicking the
mouse, pressing a key or resetting a form. When triggered, events can be used to run functions.
Lastly and not quite so obvious is referencing. This is about working out what to write to access
the contents of objects or even the objects themselves.As an example, think of the following situation. A
person clicks a submit button on a form. When they click the button, we want to check if they have filled
out their name in a text box and if they have, we want to submit the form. So, we tell the form to detect
the submit event. When the event is triggered, we tell it to run the function that holds together the tests
and actions. The function contains a control structure that uses a comparison operator to test the
text box to see that it is not empty. Of course we have to work out how to reference the text box first.
The text box is an object. One of the variables it holds is the text that is written in the text box. The text
written in it is a literal. If the text box is not empty, a method is used that submits the form.

3. Operators
The most common operators are mathematical operators; +, -, /, * (add, subtract, divide, multiply)
for example. Operators can be split into two groups, comparison operators and assignment or 'action'
operators. Comparison operators test to see if two variables relate to each other in the specified way, for
example, one variable is a higher number than the other. Other operators perform an action on a variable,
such as increasing it by one.
The following table gives those that are most commonly used. The JavaScript 1.3 operators such
as the identity operator === are supported by all current browsers, but are not used as often as the others.
Old browsers that do not understand them will just produce errors.

JavaScript operators
Operator Uses
adds two numbers or appends two strings - if more than one type of variable is appended,
+
22

JavaScript operators
Operator Uses
including a string appended to a number or vice-versa, the result will be a string
subtracts the second number from the first
divides the first number by the second
/
multiplies two numbers
*
divide the first number by the second and return the remainder
%
assigns the value on the right to the object on the left
=
the object on the left = the object on the left + the value on the right - this also works when
+=
appending strings
the object on the left = the object on the left - the value on the right
-=
number on the left must be greater than the number on the right - this also works with strings
>
and values
number on the left must be less than the number on the right - this also works with strings and
<
values
number on the left must be greater than or equal to the number on the right - this also works with
>=
strings and values
number on the left must be less than or equal to the number on the right - this also works with
<=
strings and values
increment the number
++
decrement the number
-the numbers or objects or values must be equal
==
the numbers or objects or values must not be equal
!=
bitwise leftshift
<<
bitwise rightshift
>>
bitwise AND
&
bitwise OR
|
bitwise XOR
^
bitwise NOT
~
logical NOT (the statement must not be true)
!
logical AND (both statements must be true)
&&
logical OR (either statement must be true)
||
object or array on the right must have the property or cell on the left
In
the numbers or objects or values must be equal, and must be the same variable type
===
the numbers or objects or values must not be equal, or must not be the same variable type
!==

Note, if you do not set the language="javascript1.2" attribute in the <script> tag, 0 == false == '' and
undefined == null. If you do set the language attribute to 'javascript1.2', Mozilla/Firefox and other Gecko
browsers (but none of the other major browsers) will change this so that none of these will equate to each
other. Since the attribute is deprecated anyway, and the JavaScript versions were never standardised, you
should not rely on this behaviour. If you need that behaviour, use the === and !== operators.
There are also a few operators that can also be used like functions:
void
23

void statement or void(statement) (see the section on writing functions)


typeof
typeof variable or typeof(variable) returns the type (or class) of a variable.
eval
eval(string) interprets a string as JavaScript code.
There are also the 'var', 'new' and 'delete' operators. See the section on variables for examples of their
uses. Also see the section on the Math object operators below.
Note that JavaScript has no logical XOR operator. If you need that functionality, see my separate
XOR article.
Operator precedence
If you ask JavaScript to perform a calculation using multiple operators, those operators will be evaluated
in a specific order. For example 3 + 6 * 7 is calculated as ( 6 * 7 ) + 3 because the * is calculated before
the +. The order in which these are evaluated is: * / % + - + (where the second + is appending strings). To
change the order in which they are calculated, use parenthesis ( ) as the contents of parenthesis are
calculated before the contents outside the parenthesis. For example, 3 + 6 * 7 = 45 but ( 3 + 6 ) * 7 = 63

The Math object methods


In reality, these are methods of the Math object but they are used in place of operators.
Math object methods
Operator
What it does
Returns the absolute value of n
Math.abs(n)
Returns (in radians) cos-1 of n
Math.acos(n)
Returns (in radians) sin-1 of n
Math.asin(n)
Returns (in radians) tan-1 of n
Math.atan(n)
Math.atan2(n,k) Returns the angle (rads) from cartesian coordinates 0,0 to n,k
Returns n rounded up to the nearest whole number
Math.ceil(n)
Returns cos n (where n is in radians)
Math.cos(n)
Returns en
Math.exp(n)
Returns n rounded down to the nearest whole number
Math.floor(n)
Returns
ln(n)
Math.log(n)
Note, to find log10(n), use Math.log(n) / Math.log(10)
Math.max(a,b,c,...) Returns the largest number
Math.min(a,b,c,...) Returns the smallest number
Returns nk
Math.pow(n,k)
Returns a random number between 0 and 1
Math.random()
Returns n rounded up or down to the nearest whole number
Math.round(n)
Returns sin n (where n is in radians)
Math.sin(n)
Returns the square root of n
Math.sqrt(n)
Returns tan n (where n is in radians)
Math.tan(n)

24

4. Variable types are not important in JavaScript. They may be interchanged as necessary. This means
that if a variable is a string one minute, it can be an integer the next. The basic variable types are:
a)character
'a' or '@' or 'k' etc.
b)string
'hdttgs 8 -46hs () Get the idea'
c) integer
0 or 1 or 2 or 3 or 4 etc. or -1 or -2 or -3 or -4 etc.
d) float (or double)
23.546 or -10.46
e) boolean
true or false

function
A function; see the section on Functions

Object
An object; see the section on Object oriented programming
Array
A type of object that can store variables in cells (see below)
Regular expression
A pattern that can be used to match strings or substrings
Undefined
A variable that has not been given a value yet
Null
A variable that has been defined but has been assigned the value of null
Integer and float are grouped together as 'number'. Character and string are grouped together as 'string'.
Use the typeof operator to find out which variable type your variable is. Note, typeof will return 'object'
for arrays, regular expressions and null in most current browsers. In future, browsers are instead expected
to return 'null' for null.
Defining variables
See the section on 'Referencing' subsection 'Avoiding referencing conflicts' to see how to choose names
for your variables.
Normal variables
It is good practice to pre-define all variables using the var keyword (this is known as declaring the
variables). It is possible to define the variable, leaving its value undefined, or assigning a value
immediately, or even to define multiple variables in a single command:
25

var variablename;
var variablename = value;
var vari1 = value, vari2 = anotherValue, vari3;
Once a variable is defined do not use 'var variablename' again unless you wish to completely overwrite
the variable. It makes no sense to redeclare a variable with the var keyword within the same scope, but
browsers will not complain if you do it.
These are some examples of how to define variables, in this case, a string, a number, and a regular
expression:
var myFish = 'A fish swam in the river';
var myNumberOfGoats = 23;
var myPattern = /<[^>]*@[^<]*>/gi;
Note that variables can be defined at any point in your script, including inside a control structure that
causes that statement never to be executed. However, no matter where you choose to define your variable,
the JavaScript engine will create the variable at the start of the current scope. It will hold the value
undefined until a statement is executed that gives it a value.
Objects
If you want to create variables that you want to be able to give child properties to, you must
define the variable as an object. To define a variable as an object, use either the new Object() or {}
syntax:
var variableName = new Object();
var variableName = {myFirstProperty:1,myNextProperty:'hi',etc};
You can then assign child objects or properties to that object as you want:
variableName.aPropertyNameIMadeUp = 'hello';
variableName.aChildObjectNameIMadeUp = new Object();
Note that if you want to run a method on an object that you just created, for true JavaScript 1.2
compliance, you must surround the object declaration with brackets (early Netscape 4 will have problems
otherwise). This example will not work in early Netscape 4, and other browsers made at the same time:
new Date().getTime()
This example will work in all JavaScript supporting browsers:
( new Date() ).getTime()
This applies to all object types like Array, Image, Option, Object, Date and ones you create yourself.
Arrays
WebTV 2.6- does not support the [] syntax for creating arrays.
Arrays are similar to the Object we have just defined, but with some small differences.
To create an array, use either the new Array() or [] syntax:
var nameOfArray = new Array();
var nameOfArray = new Array('content_of_first_cell','and_the_second',8,'blah','etc');
var nameOfArray = ['content_of_first_cell','and_the_second',8,'blah','etc'];
We can also use a single number as a parameter when creating the array object. If the number is a
positive integer, an array will be created with that many cells, all of which will be empty: new Array(5).
Note that if you set the language version to javascript1.2, some browsers (but not all) will create an array
with a single cell containing the number 5. For this reason, it is best not to use a single numeric parameter
when creating the array using the new Array(number) syntax.
26

To refer to the contents of its cells, use the syntax nameOfArray[name_or_number_of_entry] (if
using names instead of numbers, the name should be in quotes). Numeric arrays start at 0, not 1, so the
first cell is number 0.

In JavaScript, arrays and objects are almost equivalent, and accessing a named cell of an array is
the same as accessing a property of an object. However, it is important to note that most of the special
array functionality is based on you using numeric arrays - most array methods act only on numeric keys,
and will ignore named properties. If you are using arrays with only named properties, then you are almost
certainly using them for the wrong reason, and should probably be using objects instead. However, for the
purpose of demonstration, if a cell of an array is called 'mycell', you could use either of these to access its
contents:
nameOfArray['mycell']
nameOfArray.mycell
There are some important differences between arrays and objects. By default, arrays have far
more methods attached to them, for stepping through a numeric array, or splitting it into pieces. In
addition, if numbers are used for entries, you can find out how many entries (or variables) the array is
holding, using nameOfArray.length
It is possible to create multi-dimensional arrays, by creating aditional arrays as the contents of the cell of
another array:
var nameOfArray = new Array(new Array(1,2,3,4),'hello',['a','b','c']);
You can refer to the cells of that array using the square bracket notation twice (or multiple times,
depending on how many dimensions your array has):
nameOfArray[name_or_number_of_entry][name_or_number_of_inner_entry]
Other types of objects
Browsers will have many built in types of objects. All JavaScript capable browsers will provide the
following aditional object types:
Date
Creates a date object, which can perform calculations based on the date, for example:
var mydate = new Date();
window.alert( 'The year is' + mydate.getFullYear() );
Image
Creates an image that is not visible but is stored in cache. Setting the src attribute of the image causes the
image to be loaded and stored in the browser's cache:
var myimage = new Image();
myimage.src = 'thing.gif';
Now each time I want to change an image on the page, I can say document['imagename'].src =
myimage.src; and the image will change, without having to wait for the new image to load.
Option
Creates an option that can be added into a select input, for example:
var myoption = new Option('text','value');
selectInput.options[selectInput.options.length] = myoption;
See the section on 'Creating objects' for how to create your own objects that are not one of the
nullVariable.itsChild = 7;
//This will throw an error

27

In the next example, the parent object has been declared, but it was not given a value. As a result, it holds
the value undefined. Trying to refer to a child property means there are now two levels of undefined
properties, and will throw an error:
The available Math object constants are:
Math object constants
Math object property Value (approx) Mathematical equivalent
2.718
e
Math.E
0.693
ln(2)
Math.LN2
2.303
ln(10)
Math.LN10
1.442
log2(e)
Math.LOG2E
0.434
log10(e)
Math.LOG10E
3.142
Pi
Math.PI
0.707
(sqrt(2))-1 or sqrt(1/2)
Math.SQRT1_2
1.414
sqrt(2)
Math.SQRT2

Special string characters


There are a few string characters that can be escaped with a backslash and can be used to replace
untypeable characters. These are:
\n
A newline character. Use this if you want to insert a line break into text.
\f
A form feed. Try not to use this ever. Use \n instead.
\r
A carriage return. Try not to use this ever. Use \n instead.
\t
A tab character.
\\
A \ character
\/
A / character (most web developers [myself included on occasion] forget this one - generally, browsers
will have no trouble with you forgetting the backslash but it is important for representing closing tags and
in theory you should always use the backslash escape when writing a forward slash - see the section on
Writing with script for details of where it is needed)
If you need to recognise a Windows linebreak, you need to look for \r\n. If you are trying to add a
linebreak (for example, when modifying the value of a textarea input), you should insert a \n character.
This will work cross browser. Note that browsers on Windows may convert this \n character into a \r\n
automatically, depending on where you use it.
Old Mac Operating Systems (OS 9 and below) used \r for linebreaks, but as far as my tests showed, they
are converted to \n by JavaScript. However, just be aware that you may encounter some of these,
especially in text inputs (Mac OS 9 is still in use among some Mac users). Unix based Operating Systems
(including Mac OS X) use \n for linebreaks.
If you are writing a string that contains double quotes, the easiest way to deal with it is to surround it with
single quotes. You should also use double quotes if your string contains single quotes:
28

var mystring = 'And he said "help" twice';


var mystring = "Help Andy's cat";
You may notice a problem. What if you have both single and double quotes in your string? The solution
is to use the escape character '\' to excape the quotes (in fact, you can always escape quotes, even if the
string is delimited by the other type of quotes). For example, both of the following are valid:
var mystring = 'And he said "help Andy\'s cat" twice';
var mystring = "And he said \"help Andy's cat\" twice";
If your string becomes too long to fit on one line (this really doesn't matter - you can make the text as
long as you want), and you want to split it onto several lines, simply end the string, follow it with the
concatenation operator + and start a new string on the next line:
var mystring = 'first line of the string ' +
'still on the first line of the string - it\'s like we never broke the line';
Note, in theory, you can use \ to break the string:
var mystring = 'like \
this';
But this has significant problems; the \ will not always cope with trailing whitespace, may or may not
correctly treat the leading whitespace before the new line, and does not work correctly in all JavaScript
implementations:

Current releases of Opera and iCab do support regular expressions correctly.


5. if .. else statement
If .. else element is a conditional statements It executes the block1 statement if the conditions
is true . the else statement is optional whose block is executed if the condition is false .The syntax is
If (condition)
{
Block;
}
{
Else
{
Block2 ;
}}
Var statement
The statements is used to declare the variables .Initialization can be done in this statement itself .The
syntax is
Var
name 1[=value1, var name2 [==value],,,,
Var x=0, y=1;

Bottom of Form
The 'if' statement
if( myVariable == 2 ) {
myVariable = 1;
} else {
myVariable = 0;
}
If myVariable had been 2 it would now be 1. If it had been anything other than 2 it would now be 0.
29

'If' statements can also test for the occurence of a child object of an object that may not exist. For
example, some browsers provide document.body.style while some older browsers do not even provide
document.body. In these browsers, writing 'if( document.body.style )' would just produce an error (see the
section on 'Variables' subsection 'Avoiding errors with variables'). In order to solve this problem, we
could write this:
if( document.body ) {
if( document.body.style ) { etc. }
}
However, the && operator has a useful feature that we can use here to combine the two 'if' statements
into one:
if( document.body && document.body.style ) { etc. }
The first test would be false, so the browser would not proceed to the second. This is known as a shortcircuit. The || operator has a similar feature, but it will only evaluate the second test if the first one fails.
JavaScript understands that if the '{' and '}' (curly brace) characters are left out, then only the next
command belongs to that statement:
if( x < 5 )
x++;
window.alert(x);
Here, the alert will always happen reguardless of x, but x will only be incremented if x is less than 5. This
may seem convenient, as it allows you to make your code a tiny bit shorter, but I recommend avoiding
this syntax. It makes your code harder to read, especially if you start nesting your control structures. It
also makes it easy to forget to put them in when you needed them, and also makes debugging code much
harder, since you will need to go back through your code to add them so that you can add extra debugging
tests. It is best to always use the curly braces, even if they are optional.
As always, there is an exception. Nested 'if' statements like this can start to get difficult to manage:
if( myVariable == 2 ) {
myVariable = 1;
} else {
if( myVariable == 5 ) {
myVariable = 3;
} else {
myVariable = 4;
}
}
By strategically removing curly braces, that can usefully be reduced to this construct (which you may
recognise from other programming languages) - note that 'else if' is not written as 'elseif':
if( myVariable == 2 ) {
myVariable = 1;
} else if( myVariable == 5 ) {
myVariable = 3;
} else {
myVariable = 4;
}
The 'for' loop
This is one of the most common constructs in use. Typically, it is used to cycle through the contents of an
array, or to create a specific number of new objects, but it can do many more useful things if needed. The
syntax of the 'for' loop is as follows:
for( starting_initialise; continue_as_long_as_condition; do_this_each_time _update)
starting_initialise
30

This is where you define new variables that you will use in the loop, typically for use with incremental
counting. As with all variables, you must declare them (if you have not done so already).We can define
multiple variables if needed, using:
var myVariable1 = value, myVariable2 = another_value;
These variables are not restricted to being inside the 'for' loop, and will be available to all code after the
loop (in the same scope as the loop).
continue_as_long_as_condition
This is where you define the conditions under which the loop should continue to execute. The syntax
is exactly the same as for the 'if' statement, so you can apply more than one continue condition by
using the && or || operators:
myVariable1 <= 5 && myVariable2 >= 70;
If the condition is not satisfied when the for loop begins, then it will never loop through it.
do_this_each_time
Once the end of the loop is reached, it will do whatever you tell it to here. Typically, this is used to
increment or decrement a stepping variable, and it is possible to perform actions on more than one
variable by separating them with a comma:
myVariable1++, myVariable2 -= 4
The following is a full example.
for( var myVariable = 1; myVariable <= 5; myVariable++ ) {
myArray[myVariable] = 1;
}
myArray[1] to myArray[5] are now 1.
The 'for - in' loop
The 'for - in' loop is used to cycle through all exposed properties of an object (or array). Every time you
create properties or methods on an object, these will be added to the list of properties that will be exposed.
Most internal properties (the ones that JavaScript creates) will also be exposed, but JavaScript engines are
allowed to hide internal properties and methods if they want to. You should not rely on any specific
behaviour here, but note that some browsers will give the internal properties and methods of intrinsic
objects, and some will not.
Again, you should declare the variable names that you use, if you have not done so already. The syntax of
the 'for - in' loop is as follows:
for( var myVariable in anObjectOrArray ) {
This will run through the loop, once for each exposed property in anObjectOrArray. Each time it loops, it
assigns the next property name as a string value to myVariable. You can then use array notation to access
the value of that property. The following example writes all the exposed properties of the document
object:
for( var myVariable in document ) {
document.write( myVariable + ' = ' + document[myVariable] + '<br>' );
}
Note that if you use this loop on an array, it will list the numbered and named keys, including the internal
'length' property. It is very easy to make mistakes here, so be careful not to mistake these property types
for each other.
The 'while' loop
While (condition)
{
Statements;
}
31

Do
{
Statements ;
}
While (condition);
Example:
m=0;
While (m<9)
{
Documents .write (m);
m++;

The 'while' loop is identical in behaviour to the 'for' loop, only without the initial setup, and loop-end
actions. It will continue to run as long as the condition is satisfied:
var myVariable = 1;
while( myVariable <= 5 ) {
myArray[myVariable] = 1;
myVariable++;
}
myArray[1] to myArray[5] are now 1.
Using a feature of the increment (and decrement) operator here, it is possible to shorten the code inside
the loop to be just 'myArray[myVariable++] = 1;', and it would have exactly the same effect. Firstly, it
would use the value of myVariable to index the array cell, then it would increment myVariable.
This also works in reverse; 'myArray[++myVariable] = 1;'. Firstly, it would increment the value of
myVariable, then it would use the new value to index the array cell. If I had done this, myArray[2] to
myArray[6] would now be 1.
These features also work outside loops, but this is where you will most commonly see them, so I have
included them here.
The 'do - while' loop
This is similar to the while loop, but with an important difference. The condition is evaluated at the end of
the loop, meaning that even if the condition is never satisfied, it will still run through the loop at least
once.
var myVariable = 1;
do {
myArray[myVariable] = 1;
myVariable++;
} while( myVariable <= 5 );
myArray[1] to myArray[5] are now 1.
The 'switch' statement
The 'switch' statement is like repeated 'if' statements, testing a single value to see if it matches one of a set
of values:
switch(myVar) {
case 1:
//if myVar is 1 this is executed
32

case 'sample':
//if myVar is 'sample' (or 1, see the next paragraph)
//this is executed
case false:
//if myVar is false (or 1 or 'sample', see the next paragraph)
//this is executed
default:
//if myVar does not satisfy any case, (or if it is
//1 or 'sample' or false, see the next paragraph)
//this is executed
}
If a case is satisfied, the code beyond that case will also be executed unless the break statement is used. In
the above example, if myVar is 1, the code for case 'sample', case false and default will all be executed as
well. The solution is to use break; as follows (The use of the break statement is described below).
switch(myVar) {
case 1:
//if myVar is 1 this is executed
break;
case 'sample':
//if myVar is 'sample' this is executed
break;
case false:
//if myVar is false this is executed
break;
default:
//if myVar does not satisfy any case, this is executed
//break; is unnecessary here as there are no cases following this
}
The 'with' statement
Take for example the following example:
x = Math.round( Math.LN2 + Math.E + Math.pow( y, 4 ) );
Using the 'with' statement, this can be replaced with:
with( Math ) {
x = round( LN2 + E + pow( y, 4 ) );
}
Note that the 'with' statement brings extra variable names into the current scope. In the example above, if
I already had a variable called pow before the 'with' statement, this variable would be unavailable inside
the with statement, as it would have been replaced by the method of the Math object (as would any other
variables that matched property or method names). Once the 'with' statement is complete, the old
variables would become available again.
The quick 'if' statement
This is known as the conditional or ternary operator, and is an easy way to assign different values to a
variable, depending on a condition.
var myVariable = document.getElementById ? 1 : 0;
This is identical to:
if( document.getElementById ) {
var myVariable = 1;
} else {
var myVariable = 0;
}
33

The try - catch - finally statement


Netscape 4, Internet Explorer 4 and WebTV do not support this structure and will produce errors if you
use it.
The 'try - catch - finally' control stucture allows you to detect errors and quietly deal with them without
producing error messages or aborting the script, and in fact, without even interrupting the flow of the
script that is running. This makes it superior to the original way of handling script errors (without error
messages) where scripts are completely aborted:
window.onerror = referenceToFunction;
The syntax of the 'try - catch - finally' control stucture is as follows:
try {
//do something that might cause an error
} catch( myError ) {
//if an error occurs, this code will be run
//two properties will (by default) be available on the
//object passed to the statement
alert( myError.name + ': ' + myError.message );
} finally {
//optional - this code will always be run before the
//control structure ends, even if you rethrow the error
//in the catch
}
If an error occurs in the 'try' section, it immediately jumps to the 'catch' part, passing some information
about the error. Different browsers provide different information for the same error so don't trust it (in
theory, DOM browsers will use a specific set of error types, but this depends on their level of DOM
support - Internet Explorer is the least compliant here). Once the 'try' or 'catch' parts have been run, the
'finally' part is run if you have provided one, then the script following the control structure is run, unless
you throw another error.
If you nest these statements (one 'try - catch' inside another), you can rethrow the error from the 'catch'
part of the inner statement to the 'catch' part of the outer statement (the 'finally' part - if there is one would still be run before the outer 'catch' is run, but the script following the inner structure will not be
run). This is done using the 'throw' method:
try{
//...some other code goes in here
try {
var a = nonexist.b; //this will produce an error
} catch(myError) {
//this catches the error and alerts the message
alert( myError.message );
//re-throw the error up to the outer try - catch
throw( myError );
}
//...some other code goes in here
} catch( myErrorObject ) {
//I re-threw the first error, so this is the same error object
//the message should be the same
alert( myErrorObject.message );
}
You can also throw your own errors at any point by creating an object with the required properties, and
passing it as the parameter when using throw:
try{
34

var myEr = new Object();


myEr.name = 'My error';
myEr.message = 'You did something I didn\'t like';
throw( myEr );
} catch( detectedError ) {
alert( detectedError.name + '\n' + detectedError.message );
}

Functions:

Functions group together script code; control structures, operations, method calls, etc. in the same way as
a normal script. These functions can then be called when needed, and the code contained within them will
be run. This makes it very easy to reuse code without having to repeat it within your script.
Functions are defined using one of these constructs:
Normal function construct
function nameOfFunction(listOfVariableNames) {
function code should be written here
}
Anonymous function, assigned to a variable
Using this syntax for object methods in early Netscape 4 versions will cause problems with the 'this'
keyword due to bugs.
nameOfFunction = function (listOfVariableNames) {
function code should be written here
};
Normal function construct, assigned to a variable
nameOfFunction = function anotherNameForTheFunction(listOfVariableNames) {
function code should be written here
};
Note that in this particular case, because the function is being assigned, and not defined normally, the
name anotherNameForTheFunction can be used by the code inside the function to refer to the function
itself, but the code outside the function cannot see it at all (note that some browsers, mainly Internet
Explorer, do not implement this correctly, so you should not rely on it - it is better to use arguments.callee
as shown below).
The Function class constructor
functionName = new Function("function code should be written here");
This construct evaluates the code as a string, and is much slower than assigning anonymous functions. It
should only be used in places where it is actually needed.
The Function class constructor with parameters
functionName = new Function("varName","varName2","etc.","function code");
See the section on 'Referencing' subsection 'Avoiding referencing conflicts' to see how to choose names
for your functions.
Functions are called using one of these:
nameOfFunction(listOfVariables);
window.nameOfFunction(listOfVariables);
35

object.onEventName = nameOfFunction;
When created using the normal function construct, the definition does not have to appear at the start of the
script (though it is usually best to do so for the sake of clarity). It can even be defined after the the code
that calls it. In most cases, no matter where you choose to define your function, the JavaScript engine will
create the function at the start of the current scope.
Note that you should never create a function using the normal function construct inside an 'if' statement
(or any equivalent control structure):
if( someCondition ) {
function functionName() {
...this will not work in most browsers...
}
}
This is permitted by Mozilla's JavaScript 1.5, but this conflicts with ECMAScript 3, the core language
used by JavaScript 1.5. As a result, Mozilla based browsers allow it, and most others do not (they will
always evaluate the function, even if the condition evaluates to false). It is best not to rely on either
behaviour, and do not try to declare functions in this way. Declaring functions inside these statements is
possible in all current browsers using assigned anonymous functions, and this is the correct way to
achieve the desired effect:
var functionName;
if( someCondition ) {
functionName = function () {
...
};
}
Passing variables to functions
Variables passed to a function are known as arguments.
When a function is called, the variables or values passed to it in the brackets are assigned to the variable
names in the brackets of the function definition.
function checkval(passvar) {
//if I ran the function using the command "checkval('hello')"
//then passvar would take on the value 'hello'
if( passvar != "" ) {
document.myform.mytextinput.value = passvar;
}
}
}

inside any other functions. If any other piece of code changes the contents of those variables, then every
other part of the code now sees the new contents. As a result, the alert here will show '7', since the value
held by the global variable is changed when the function is run.
Variable d is defined inside the sample function, so it is not global. It is in the local scope of the function.
What that means is that only the code inside the function can see it. Code outside the function does not
even know it exists. This happens with any function. They have the ability to create their own scopes, and
their own local variables, without them interfering with variables located in the global scope. Variable
names written in the brackets of the function definition are also created as variables in the local scope
(and the same applies to the arguments collection):
function sample(myvar) {
//myvar is now a variable in the local scope
alert(myvar);
36

}
sample('hello');
Now try this modification to the earlier code:
var a = 1, b = 2, c = 3;
function sample() {
var a, d;
a = 7;
}
sample();
alert(a);
Here, the variable a is redefined inside the function. Because it is declared using the var keyword, it
becomes a local instance of a variable. Even though it shares the same name as a global variable, the two
are completely independent. The changes made to that variable inside the function only affect the local
variable, not the global one. As a result, the alert will show '1', and not '7'.
Now imagine that the code inside the function wants to reference the global variable 'a' instead of the
local one. The global scope is special. In JavaScript, the global scope can be referenced using the name
'window'. The code inside the function can use window.a to reference the global 'a' variable. Incidentally,
this is why methods like alert can be called using either alert or window.alert, since these methods are
globally available (unless they are overwritten in the current scope, of course).
Nested functions
It is possible to create functions inside other functions. Simply declare another function inside the code of
an existing function:
var a = 1, b = 2, c = 3;
function sample() {
var a, d, e;
function anothersample() {
var e, f;
}
anothersample();
}
sample();
In that example, the anothersample function only exists inside the sample function, and it can only be
called by the code inside the sample function. Code outside that function does not even know it exists.
The scopes are also nested, so the code inside the anothersample function has access to b and c from the
global scope, a and d from the sample scope, and then e and f from its own local scope. It can also use
window.a to reference the variable a from the global scope.
Of course, if you assign a reference to the nested function to a global variable, then the function can be
accessed globally through that variable. There is not much point in doing that here, but it becomes very
useful when creating object methods (these will be covered in detail in a later chapter).
Scopes have memory
Scopes are actually very clever, since they persist over time. Imagine that the code inside a function
creates a local variable. It also creates an event handler function that will be triggered when the user
clicks a link:
function sample() {
var a = 20;
document.links[0].onclick = function () {
alert(a);
};
}
sample();
37

The action that calls the event handler (inner) function happens much later, a long time after the script
that created it has finished running. However, the variable 'a' has survived, so the alert will display the
number 20.
Using scope to prevent conflicts
Imagine that you are running a script that uses many global variable and function names. You want to put
another script on the same page, but there is a chance that the two scripts will use the same variable
names as each other, and may conflict. It is easy to workaround this problem by putting the code from
each script inside a function, and running the function. That way, the local scope provided by the function
will protect the variables overwriting each other in the global scope. Note that when doing this, it is very
important that you remember to declare your variables properly.
The easy way to do this without creating a global function is to create an anonymous function, and
enclosing it in parenthesis (internally, the engine will then replace that entire construct with the function
reference). You can then use the open-close parenthesis to run it immediately. This construct may look a
little odd, but it works:
(function () {
//Put your script code in here
})();
Using nested function scope to preserve instantaneous values
This is an advanced topic that is covered in its own article.
6.
<html>
<head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<h1>My First Website : www.w3schools.com</h1>
<h2> Click the display date </h2>
<p id="demo">JAVASCRIPT</p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>

OBJECTS OF JAVASCRIPTS

What is the Document Object Model?


The Document Object Model (DOM) is a cross-platform and language-independent convention for
representing and interacting with objects in HTML, XHTML and XML documents.[1] Aspects of the
DOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming
38

language in use. The public interface of a DOM is specified in its application programming interface
(API).v
The Document Object Model is a platform- and language-neutral interface that will allow programs and
scripts to dynamically access and update the content, structure and style of documents. The document can
be further processed and the results of that processing can be incorporated back into the presented page.
This is an overview of DOM-related materials here at W3C and around the web.
Why the Document Object Model?
"Dynamic HTML" is a term used by some vendors to describe the combination of HTML, style sheets
and scripts that allows documents to be animated. The W3C has received several submissions from
members companies on the way in which the object model of HTML documents should be exposed to
scripts. These submissions do not propose any new HTML tags or style sheet technology. The W3C
DOM Activity is working hard to make sure interoperable and scripting-language neutral solutions are
agreed upon.

Introduction
The Document Object Model (DOM) is an application programming interface (API) for valid HTML and
well-formed XML documents. It defines the logical structure of documents and the way a document is
accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense increasingly, XML is being used as a way of representing many different kinds of information that may
be stored in diverse systems, and much of this would traditionally be seen as data rather than as
documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage
this data.
With the Document Object Model, programmers can build documents, navigate their structure, and add,
modify, or delete elements and content. Anything found in an HTML or XML document can be accessed,
changed, deleted, or added using the Document Object Model, with a few exceptions - in particular, the
DOM interfaces for the XML internal and external subsets have not yet been specified.
As a W3C specification, one important objective for the Document Object Model is to provide a standard
programming interface that can be used in a wide variety of environments and applications. The DOM is
designed to be used with any programming language. In order to provide a precise, language-independent
39

specification of the DOM interfaces, we have chosen to define the specifications in Object Management
Group (OMG) IDL [OMG IDL], as defined in the CORBA 2.3.1 specification [CORBA]. In addition to
the OMG IDL specification, we provide language bindings for Java [Java] and ECMAScript
[ECMAScript] (an industry-standard scripting language based on JavaScript [JavaScript] and JScript
[JScript]). Because of language binding restrictions, a mapping has to be applied between the OMG IDL
and the programming language in used. For example, while the DOM uses IDL attributes in the definition
of interfaces, Java does not allow interfaces to contain attributes:
// example 1: removing the first child of an element using ECMAScript
mySecondTrElement.removeChild(mySecondTrElement.firstChild);
// example 2: removing the first child of an element using Java
mySecondTrElement.removeChild(mySecondTrElement.getFirstChild());

What the Document Object Model is


The DOM is a programming API for documents. It is based on an object structure that closely resembles
the structure of the documents it models. For instance, consider this table, taken from an XHTML
document:
<table>
<tbody>
<tr>
<td>Shady Grove</td> <td>Aeolian</td>
</tr> <tr>
<td>Over the River, Charlie</td>
<td>Dorian</td>
</tr>
</tbody>
</table>

A graphical representation of the DOM of the example table, with whitespaces in element content (often
abusively called "ignorable whitespace") removed, is:

40

The history of the Document Object Model is intertwined with the history of the "browser wars" of the
late 1990s between Netscape Navigator and Microsoft Internet Explorer, as well as with that of JavaScript
and JScript, the first scripting languages to be widely implemented in the layout engines of web browsers

DOM Interfaces and DOM Implementations


The DOM specifies interfaces which may be used to manage XML or HTML documents. It is important
to realize that these interfaces are an abstraction - much like "abstract base classes" in C++, they are a
means of specifying a way to access and manipulate an application's internal representation of a
document. Interfaces do not imply a particular concrete implementation. Each DOM application is free to
maintain documents in any convenient representation, as long as the interfaces shown in this specification
are supported. Some DOM implementations will be existing programs that use the DOM interfaces to
access software written long before the DOM specification existed. Therefore, the DOM is designed to
avoid implementation dependencies; in particular,
1. Attributes defined in the IDL do not imply concrete objects which must have specific data
members - in the language bindings, they are translated to a pair of get()/set() functions, not to a
data member. Read-only attributes have only a get() function in the language bindings.
2. DOM applications may provide additional interfaces and objects not found in this specification
and still be considered DOM conformant.
3. Because we specify interfaces and not the actual objects that are to be created, the DOM cannot
know what constructors to call for an implementation. In general, DOM users call the createX()
methods on the Document class to create document structures, and DOM implementations create
their own internal representations of these structures in their implementations of the createX()
functions.
The Level 2 interfaces were extended to provide both Level 2 and Level 3 functionality.
41

DOM implementations in languages other than Java or ECMAScript may choose bindings that are
appropriate and natural for their language and run time environment. For example, some systems may
need to create a Document3 class which inherits from a Document class and contains the new methods
and attributes.

Figure: A view of the DOM Architecture

Objects of java scripts:

BROWSER OBJECTS:
Window Object Properties

Property

Description

closed

Returns a Boolean value indicating whether a window has been closed or not
42

defaultStatus

Sets or returns the default text in the statusbar of a window

document

Returns the Document object for the window (See Document object)

frames

Returns an array of all the frames (including iframes) in the current window

history

Returns the History object for the window (See History object)

innerHeight

Sets or returns the the inner height of a window's content area

innerWidth

Sets or returns the the inner width of a window's content area

length

Returns the number of frames (including iframes) in a window

location

Returns the Location object for the window (See Location object)

name

Sets or returns the name of a window

navigator

Returns the Navigator object for the window (See Navigator object)

opener

Returns a reference to the window that created the window

outerHeight

Sets or returns the outer height of a window, including toolbars/scrollbars

outerWidth

Sets or returns the outer width of a window, including toolbars/scrollbars

pageXOffset

Returns the pixels the current document has been scrolled (horizontally) from the
upper left corner of the window

pageYOffset

Returns the pixels the current document has been scrolled (vertically) from the
upper left corner of the window

parent

Returns the parent window of the current window

screen

Returns the Screen object for the window (See Screen object)

screenLeft

Returns the x coordinate of the window relative to the screen

screenTop

Returns the y coordinate of the window relative to the screen

screenX

Returns the x coordinate of the window relative to the screen


43

screenY

Returns the y coordinate of the window relative to the screen

self

Returns the current window

status

Sets the text in the statusbar of a window

top

Returns the topmost browser window

Window Object Methods


Method

Description

alert()

Displays an alert box with a message and an OK button

blur()

Removes focus from the current window

clearInterval()

Clears a timer set with setInterval()

clearTimeout()

Clears a timer set with setTimeout()

close()

Closes the current window

confirm()

Displays a dialog box with a message and an OK and a Cancel button

createPopup()

Creates a pop-up window

focus()

Sets focus to the current window

moveBy()

Moves a window relative to its current position

moveTo()

Moves a window to the specified position

open()

Opens a new browser window

print()

Prints the content of the current window

prompt()

Displays a dialog box that prompts the visitor for input

resizeBy()

Resizes the window by the specified pixels

resizeTo()

Resizes the window to the specified width and height

44

scroll()
scrollBy()

Scrolls the content by the specified number of pixels

scrollTo()

Scrolls the content to the specified coordinates

setInterval()

Calls a function or evaluates an expression at specified intervals (in milliseconds)

setTimeout()

Calls a function or evaluates an expression after a specified number of milliseconds

Frames property:
Definition and Usage
The frames property returns an array of all the frames (including iframes) in the current window.
Syntax:
window.frames
Example: Find the number of frames on a page , and change the src property of every frame element to
W3schools.com
<html> <body>
<iframe src="http://microsoft.com"></iframe>
<iframe src="http://google.com"></iframe>
<iframe src="http://youtube.com"></iframe>
<script type="text/javascript">
for (var i=0; i<frames.length; i++)
{
frames[i].location="http://w3schools.com"
}
</script>
</body> </html>
Length Property: The length property is supported in all major browsers.
Example
<html>
<body>
<iframe src="http://microsoft.com"></iframe>
<iframe src="http://google.com"></iframe>
<iframe src="http://youtube.com"></iframe>
45

<script type="text/javascript">
for (var i=0; i<frames.length; i++)
{
frames[i].location="http://w3schools.com"
}
</script>
</body>
</html>

Form object
Form enctype Property
The enctype property sets or returns the value of the enctype attribute in a form.
The enctype attribute specifies how form-data should be encoded before sending it to the server.
The form-data is encoded to "application/x-www-form-urlencoded" by default. This means that all
characters are encoded before they are sent to the server (spaces are converted to "+" symbols, and special
characters are converted to ASCII HEX values).
Syntax
formObject.enctype=value
The enctype property can have one of the following values:
Value

Description

application/x-www-form-urlencoded

All characters are encoded before sent (this is default)


46

multipart/form-data

No characters are encoded. This value is required when you


are using forms that have a file upload control

text/plain

Spaces are converted to "+" symbols, but no special characters


are encoded

The enctype property is supported in all major browsers.


Note: Internet Explorer and Safari returns "application/x-www-form-urlencoded" even if no enctype
attribute is defined (this is the default value), while the other browsers return nothing.
Example
Name : the name of the form as defined in the html <form> tag when the form is created for example:
<form name =myform>
It can be accessed using Javascript .ex
form use the following code.

if it is the third form in the document to obtain the name of this

Alert (documents.forms[2].name);
Method : Used to submit the information in the form as defined in the html <form> tag when the
form is created for ex
<form methods=POST>
Post or set property can be accessed using the javascript
Alert (document.forms[2].methods];
Action : The action to be taken when the form is submitted as defined in the html <form> tag when
the form is created.
<form action = mailto: sales@bigco.com>
Alert (document.forms[2].action );
Will display the action property of the example form
Length the number of length (text boxes , button ) in the firm .for example
Alert (document.forms[2]. Length); helps to display the number of elements in this form
Elements : An array of all the number on the form. Individual elements are referenced by index
number .Element ae automatically numbered from 0 starting at the beginning of the form .
Alert(document.forms[2]. Elements [0]. Name );
Form methods include:
Submit ()

47

Submits the form data to the destination specified in the action attribute using the method specified
in the methods attribute As Such it performs exactly the same function in the method sttribute .As
such it perform exactly the same function as a standard submit button but it allows the
programmer greater flexibility .
Form EVENTS include:
Onsubmit : Messagfe sent each ti,e a form is submitted .Can be used to trigger actions
(eg: calling a function ) usually placed within the <form> tags
<form onSubmit =displayOK()>
**************
Text boxes and Text-areas
Each element within a form is an object in its win right and each has properties methods and
events that can be accessed using javascript .Text box and text area properties includes
Name : The name of text box or text area as defined in the HTML <input> tag when the form is
created for ex:
<input type =text name = text box1>
The name property of a text box or other form element can be accessed using javascript in this
manner shown under the section on document .length above.
Value : The text typed into a text box by the user. The text box os named textbox1. Therefore we
can obtain any text typed into to using the code:
Alert(document .forms[2].textBox1.value);
Text boxes and Text-areas events include:
OnFocus :Event signal generated when a user clicks in a text bos or text area.This text box was
declared using the following HTML code.
<input type = text name =text box2 onfocus =alertOnFocus( )>
OnBlur : Event signal generated when a user click outside a text box or text area having
previously clicked inside it . This text box was declared using the following HTML code .
<input type = text name =text box3 onBlur =alertOnBlur( )>
This function called alertOnBlur ( ) display an alert box sp clicking in the text box above and then
clicking outside it should trigger the function and cause the alert to appear.
Button ,RadioButton and checkboxes:
Button ,RadioButton and checkboxes properties includes:
Name : The name of button ,radio button and checkboxes as defined in the HTML <input> tag
when the form is created for ex:
<input type = button name = button1>
Value:The value given to the button when it is created. On standard buttons the value is displayed
as a label .On radio button and checkboxes the value is not displayed . This button is named button1
and has the value original value , original lable, We can change the value of the button and hence its lable
using the code:

48

Document .forms[2].button1.value = new value , new label;


Checked : Checkbox is named as checkbox 1. We can determine whether ithas been selected or not
using the following code.
If document .forms[2].checkbox1.checked== true)
{

Alert(checked);

}
Else
{

Alert (not checked)

};
Button ,Radio-button and checkbox methods include:
Focus( )

Default button will be activated of the return key is pressed.


document .forms[2].button2.focus( );

Blur ( ) Removes focus from a buton .for example the code


document .forms[2].button2.blur( );
Click ( )

The effect of clicking a button


document .forms[2].button2.click( );

Button ,Radio-button and checkbox Events include


Onclick:
Signal sent when the button is clicked .This can be used to call a function and is probably the most
frequently and its probably the most frequently used of all the button events EX:
<input type = button name = button3 value = click Here onClick= alert (onClick event received)
>
OnFocus:
Signal sent when the button receives focus . For ex: a button was declared using the
following code:
<input type = button name = button3 value = click Here onFocus =alert ( this button is no longer
the default)>
OnBlur : Signal sent when the button loses focus .for example a button is declared using the following
code
<input type = button name =button 5 value =click here onBlur =alert(this button is no longer the
default)>
THE SELECT OBJECT :
Selection boxes behaves in a very similar fashion to radio button they present several options of
which only one can be selected at a time .they also have a similar set of properties methods and events .
the principal difference form a programming perspective is that selection boxes do not have a checked
property .Instead to find out which option has been selected one must use the selected index property.
SelectedIndex:
49

Returns an integer indicating which one form a group of options has been selected by the
user.
Alert (documents.forms[2].selectBox1.selectedIndex);
OTHER OBJECTS:
In addition to the objects that are already discussed there are a number of them objects
that form part of the Javascript language . Among the more important and useful of these
are the Date and Math objects.
5.4.1 The Date objects:
Data object allow us to obtain the current date and time and to perfor various timing operations .In
order to use the data object we must first create a new instance of it ./this is done in the following
way.
Var mydataObject = new Date ;
This creates an object called myDataObject that contain information about the date time etc.,
Methods

Description

getFull Year( )

Returns the current year as a four digit number (eg 2002

Get Month()

Returms the current month as an integer from 0-11


Ex November =10

Get Date ( )

Returns of the day of the month as an integer between between 0


and 6 starting form Sunday

getDay( )

REtuns the day of the wek as an integer between 0to 6 starting


from Saturday ( eg Tuesday =2)

get Hours( )

Returns the hour of the day as an integer between 0 and 23

getMinutes( )

Returns the number of seconds since the start of the minute as an


integer

getSeconds( )

Returns the number of seconds since the start of the minute as


an integer

<html>
<head>
<title> ex for data object </title>
<script language =javascript>
Var myDateObject = new Date;
Var currentDay=myDataObject.getDay( );
Alert(currentDay);
</script>
50

</head>
<body>
</body>
</html>

Math OBJECT
Math object allows us to perform various mathematical operatioin that are not provided by the
basic operators we have already looked at . Its methods include the following as shown in the table.
Methods

Description

Sqrt (x)

Returns the square root of x

Log (x)

Returns the natural logarithms of x

Max (x,y)

Returns whixhever is the larger of x and y

The math object also has methods to perform trigonometrical operations such as sin(), cos() tan(), etc.,
and to set of properties that includes values for pi and other constants
EXAMPLES:
Write ascript to add two interger
<html>
<head>
<title> To add two integer </title>
<script language = javascript>
Var no , no1, no2, no3, result ;
no= window.prompt(enter the 1st number);
no2= parseInt(no);
no3 = parseInt(no1);
result= no2+no3;
document.write\n ( <h3> 1 st number = + no2+</h3><br>);
document.write\n ( <h3> 2 rd number = + no3+</h3><br><br>);
document.write\n ( <h1> Result is = +result+</h2>);
</script></head><body>
</body>
51

</html>
*****************************
UNIT IV :

Dynamic HTML with Javascript

1. DHTML Introduction
Every web page in the world uses HTML (the Hyper Text Markup Language) - it's a formatting
language that tells a web browser whether the contents of a web page should be in bold, large or small,
tabulated or in paragraphs. However, HTML is a static language - once it's been loaded into a web page
then it won't change; unless, of course, it's Dynamic HTML.
Dynamic HTML works because of the fact that when web page is viewed in a web browser (such as
Microsoft Internet Explorer or Mozilla Firefox) it is not just formatted text - it is actually a set of objects,
a set of objects that can be manipulated using a programming language such as Javascript; and the most
important of the objects to is the document.

DHTML :
DHTML is NOT a language.
DHTML stands for Dynamic HTML.
DHTML is NOT a language or a web standard.
DHTML means the combination of HTML, JavaScript, DOM and CSS.
DHTML is a TERM describing the art of making dynamic and interactive web pages.

DHTML is the art of combining HTML, JavaScript, DOM, and CSS.


Before you continue you should have a basic understanding of the following:
HTML
CSS
JavaScript
According to the World Wide Web Consortium (W3C):
"Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and
scripts that allows documents to be animated."

HTML
The W3C HTML 4 standard has rich support for dynamic content:
HTML supports JavaScript
52

HTML supports the Document Object Model (DOM)


HTML supports HTML Events
HTML supports Cascading Style Sheets (CSS)
DHTML is about using these features, to create dynamic and interactive web pages.

JavaScript
JavaScript is the most popular scripting language on the internet, and it works in all major browsers.
DHTML is about using JavaScript to control, access and manipulate HTML elements.

HTML DOM
The HTML DOM is a W3C standard. It describes the Document Object Model for HTML.
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
DHTML is about using the DOM to access and manipulate HTML elements.
We can read more about the HTML DOM in a later chapter of this tutorial.
HTML Events
HTML events are a part of the HTML DOM.
DHTML is about creating web pages that reacts to (user)events.
DHTML - JavaScript
JavaScript can create dynamic HTML content. In JavaScript, the statement: document.write(), is used to
write output to a web page.
Example: 1
The following example uses JavaScript to display the current date and time on a page

53

DHTML - HTML DOM


What is the HTML DOM?
The HTML DOM is:
A Document Object Model for HTML
A standard programming interface for HTML
Platform- and language-independent
A W3C standard
The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface)
to access them.
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
Change an HTML Element :

Example 2

The following example changes the content of an h1 element:

The HTML document above contains an h1 element with id="header"


We use the HTML DOM to get the element with id="header"
A JavaScript changes the content (innerHTML) of that element
54

Example 3:

DHTML - HTML Events


HTML events can trigger actions in a browser.
HTML Events
Every element on an HTML page has events which can trigger a JavaScript.
For example, we can use the onClick event of a button element to indicate that a function will run when a
user clicks on the button. We define the events in the HTML tags.

Examples of events:
A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input field in an HTML form
Submitting an HTML form
A keystroke
In the following example, the content of the h1 element will change when a user clicks on it:
Example 1.1

55

When click on this text is pressed you can observe the result
Example 1.2

You can also add the script in the head section, and then call a function from the event handler:
<html>
<head>
<script type=text/Javascript>
Function changetext(id)
{ id.innerHtml=Ooops!;
}

56

PROGRAM
EVENT :ONCHANGE

57

TEXT : ATTRIBUTE : EXAMPLE

Change the background color of an input field.

58

Changing the background images

DHTML - CSS

JavaScript and the HTML DOM can be used to change the style of any HTML element.
Change Style of the Current HTML Element
To change the style of the current HTML element, use the following statement: this.style.property=new
style

When click Me! Is clicked we can observe the result as follows:

59

Example for Mouse event .

Visibility

When the hide text is clicked the data are hidden

60

When the show text button is pressed the message will appear .

61

UNIT 5

Extensible Mark -Up Language

It is a markup Language(XML) is a markup language much like HTML .Both XML and HTML
are based on Standard Generalized markup language(SGML) SGML was developed in 1970 was used by
organization like IRS ,IBM and DEPARTMENT of DEFENCE .
SGML focuses on content structure .This language is good for createing catalogues , manuals etc., XML
is called as Meta language because it can create other mark up languages .This language was designed to
described data and its tags are not pre-defined .XML uses a DTD to dormallydescribe the data .It acts as
an infrastructure because it is the core building block for a wide range of other technologies.

XML is the basis for a family of standards including


XML Namespaces
XML Scheme
Xlink XPATH
XQUERY
Resources Description Framework(RDF) /Semantic web
RSS (Really simple Syndication)
XML Files
Raw XML files can be viewed in all major browsers.
What Is XHTML?

XHTML stands for EXtensible HyperText Markup Language

XHTML is almost identical to HTML 4.01

XHTML is a cleaner version of HTML

XHTML is HTML defined as an XML application

XHTML is a W3C Recommendation

62

XML For different output:

Sound Document

SYNTAX of the document :


<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>

</to>
63

<from>

</from>

<heading>

</heading>

<body>

</body>

</note>
Viewing XML Files
<?xml version="1.0" encoding="ISO-8859-1"?>
- <note>
<to> SURESH</to>
<from>GANESH</from>
<heading>BIRTHDAY WISHES </heading>
<body>MANY MORE HAPPY RETURN OF THE DAY</body>
</note>
HTML VS XML
XML is not a replacement for HMTL . In fact they are used together. XML and HTML were designed
with different goals.
XML was designed to describe data and to focus on what data is HTML was designed to display data and
to focus on how data looks Html is about displaying information whereas XML is about describing
information.
XML Tree
XML documents form a tree structure that starts at "the root" and branches to "the leaves".
An Example XML Document
XML documents use a self-describing and simple syntax:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to> SURESH</to>
<from>GANESH</from>
<heading>BIRTHDAY WISHES </heading>
</body>
</note>
The first line is the XML declaration. It defines the XML version (1.0) and the encoding used (ISO-88591 = Latin-1/West European character set).
The next line describes the root element of the document (like saying: "this document is a note"): <note>
The next 4 lines describe 4 child elements of the root (to, from, heading, and body):
64

<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
And finally the last line defines the end of the root element: </note>
From this example, that the XML document contains a note to Tove from Jani.
XML Documents Form a Tree Structure
XML documents must contain a root element. This element is "the parent" of all other elements.
The elements in an XML document form a document tree. The tree starts at the root and branches to the
lowest level of the tree.
All elements can have sub elements (child elements):
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
The terms parent, child, and sibling are used to describe the relationships between elements. Parent
elements have children. Children on the same level are called siblings (brothers or sisters).
XML Attributes
XML elements can have attributes, just like HTML. Attributes provide additional information about an
element.
<img src="computer.gif"> <a href="demo.asp">
Attributes often provide information that is not a part of the data. In the example below, the file type is
irrelevant to the data, but can be important to the software that wants to manipulate the element:
<file type="gif">computer.gif</file>
XML Attributes Must be Quoted
Attribute values must always be quoted. Either single or double quotes can be used. For a person's sex,
the person element can be written like this:
<person sex="female"> or like this: <person sex='female'>
XML Elements vs. Attributes
Take a look at these examples:
<person Gender="Female">
<firstname> PRAJNA </firstname>
<lastname> SARMATHA </lastname>
</person>
<person>
<Gender>Female</Gender>
65

<firstname>PRAJNA </firstname>
<lastname> SARMATHA </lastname>
</person>
In the first example Gender is an attribute. In the last, Gender is an element. Both examples provide the
same information.
There are no rules about when to use attributes or when to use elements. Attributes are handy in HTML.
In XML my advice is to avoid them. Use elements instead.
Our Favorite Way
The following three XML documents contain exactly the same information:
A date attribute is used in the first example:
<note date="10/01/2008">
<to> SURESH</to>
<from>GANESH</from>
<heading>BIRTHDAY WISHES </heading>
<body>MANY MORE HAPPY RETURN OF THE DAY</body>
</note>
A date element is used in the second example:
<note>
< date>=4/26/2011</date>
<to> SURESH</to>
<from>GANESH</from>
<heading>BIRTHDAY WISHES </heading>
<body>MANY MORE HAPPY RETURN OF THE DAY</body>
</note>
An expanded date element is used in the third: (THIS IS MY FAVORITE):
note>
<date>
<day>26</day>
<month>04</month>
<year>2011</year>
</date>
<to> SURESH</to>
<from>GANESH</from>
<heading>BIRTHDAY WISHES </heading>
<body> MANY MORE HAPPY RETURN OF THE DAY </body>
66

</note>
XML Validator
Use our XML validator to syntax-check your XML.
HTML browsers will display documents with errors (like missing end tags). HTML browsers are big and
incompatible because they have a lot of unnecessary code to deal with (and display) HTML errors.
With XML, errors are not allowed.

Syntax-Check Your XML

To help you syntax-check your XML, we have created an XML validator.


Paste your XML into the text area below, and syntax-check it by clicking the "Validate" button.

Note: This only checks if your XML is "Well formed". If you want to validate your XML against a DTD,
see the last paragraph on this page.
XML DTD: DTD is to define the legal building blocks of an XML document.It defined the document
strucrure with a list of legal elements .A DTD can be declared inline in XML document or as external
reference
Internal DTD:
The following is an XML document with a Document Type definition
< ? XML version =1.0?>
<! DOCTYPE NOTE
{
<! ELEMENT NOTE (to , from, heading , body)>
<!ELEMENT TO (#PCDATA)>
<!ELEMENT FROM (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body(#PCDATA)>
]>
<note>
<to > SURESH</to>
<from>GANESH</from>
<heading> BIRTHDAY WISHES</heading >
<body> MANY MORE HAPPY RETURNS OF THE DAY</Body>
</note>
External DTD:
This is the same XML document with an external DTD:
<?xml version =1.0?>
<!DOCTYPE NOTE SYSTEM NOTE>DTD>
67

<note>
<to> SURESH</to>
<from>GANESH</from>
<heading> BIRTHDAY WISHES</heading >
<body> MANY MORE HAPPY RETURNS OF THE DAY</Body>
This is copy of the file note.dtd containing the document type definition
<?xml version =1.0?>
<! ELEMENT note (to,from, heading ,body)>
<!Element to (#PCDATA)>
<!Element from(#PCDATA)>
<!Element heading (#PCDATA)>
<!Element body(#PCDATA)>
Why to use a DTD?
XML provide an application independent way of sharing data .With a DTD independent groups of people
can agree to use a common DTD for interchanging data .Anuone can use a standard DTD to verify that
data is his application that he receives form the outside world is valid. You can also use a DTD to verify
your own data
Building Blocks of XML Documents
Xml documents and HTML documents are made up of the following building
Elements
Tags
Attributes
Entities
PCDATA
CDATA
Elements
Elements are the main building blocks of both XML and HTML documents .Examples of HTML
elements are body and table . Examples of xml elements can be mote and message .Elements can contain
text other elements or be empty.empty elements are the elements without the closing tag. They should be
defined as <./>
Example ofempty HTML elements are hr, br, and img
TAGS:
Tags are used to mark up elements .A starting tag like <elements _name> mark up the beginging of an
elements and an editing tag like</element_name> marks up the ends of an elements
Some example are
A body element: < body> body text in between </body>
A message element : <message > some message in between</Message>
Attributes:
68

It provide extra information about elements.Attributes are palces inside the start tag of an element
.Attributes come in name /value pairs. The following img element has an additional information about a
source file
< img src =computer.gif/>
The name of the element is img . the name of the attribute is SRC. The value of the attribute is
computer.gif .Since the element itself is empty it is closed it is closed by /
PCDATA
IT means Parsed Character Data .PCDATA is text that will be parsed by a parser. Tags inside the text
will be treated as markup and entities will b e expanded
CDATA
CDATA also meand character data .CDATA is text that does not get parsed by a parser.Tags inside the
text will not be treated as markup and entities will not be expanded.
Entities:
Entities as variable used to define common text. Entity references are references to entities. &nbsp. That
is used to insert an extra space in an HTML document is an ex of the HTML entity reference.Entities are
expanded when a document is parsed by an XML PARSER.
DTD Element:
Declaring an element
In the DTD XML elements are declared with an element declaration. An element declaration has the
following syntax.
! ELEMENT element _name (element-content)>
Ex: ! ELEMENT note(to, from, heading ,body)>
Empty Elements:
This element are declared with the keyword empty inside the parentheses. ELEMENT element name
(EMPTY)>
ELEMENTS WITH DATA
ELEMENTS WITH DATA ARE DECLARED WITH THE DATATYEP inside PARentheses:
<!ELEMENT Element_name(#CDATA)>
Or
<!ELEMENT Element_name(#PCDATA)> or <!ELEMENT Element_name(ANY)>
EXAMPLE :
<!ELEMENT Element_name(#PCDATA)>
#CDATA means the element contain character data that is not supposed to be parsed by a parser.
#PCDATA means that the element contain data that is going to be parsed by a parser. The keyword any
declares an element with any content .if a #PCDATA section contain elements these elements must also
be declared .
ELEMENTS with Children(sequences)
Elememts with one or more children are defined with the name of the children elements inside the
paratheses.
< !ELEMENT Element_name( child-elements-name)>
69

Or
< !ELEMENT Element_name( child-elements-name, child-element-name ,)>
Example < !ELEMENT note(to, from, heading ,body)>
When children are declared in a sequence separated by commas. The children must appear in the sma
sequence in the document .In a full declaration the children must also be declared. And the children can
also have children. The full declaration of the note document will be
<! ELEMENT note (to, from, heading ,body)>
<!ELEMENT to (#CDATA)>
<!ELEMENT from (#CDATA)>
<!ELEMENT heading (#CDATA)>
<!ELEMENT body(#CDATA)>
WRAPPING
IF the DTD is to be included in the XML source file It should be wrapped in a DOCTYPE definition with
the following syntax.
<! DocTYPR root-element (element_declaration)>
Example:
<?xml version=1.0?>
<!DOCTYPE note [
<! ELEMENT note (to, from, heading ,body)>
<!ELEMENT to (#CDATA)>
<!ELEMENT from (#CDATA)>
<!ELEMENT heading (#CDATA)>
<!ELEMENT body(#CDATA)>
]><note>
<to> SURESH</to>
<from> GANESH</from>
<heading >BIRTHDAY WISHES</heading >
<body> MANY MORE HAPPY RETURNS OF THE DAY</body>
DECLARING ONLY ONE OCCURRENCE OF THE SAME ELEMENT
< !ELEMENT Element_name( child-name)>
EXAMPLE:
<! ELEMENT note (MESSAGE)>
We can declares that the child element message can only occur once inside the note elements
DECLARING MINIMUM ONE OCCURRENCE OF THE SAME ELEMENT
<! ELEMENT Element_name (child_name+)>
Example
70

<! Element Note (message+)>


+ sign in the example above declares that the child element message must occur one or more times inside
the note element
DECLARING ZERO or ONE OCCURRENCE OF THE SAME ELEMENT
<! ELEMENT Element_name (child_name+)>
EXAMPLE:
<! ELEMENT note (message*)>

Sign in the example above declares that the child element message can occur zero or more times
inside the note element
DECLARING MIXED Content
<! Element note ( to + , from , header , message * , #PCDATA)>
It declares that te element note must contain at least one child element exactly one from child elements
exactly one header zero or mote messages and some other parsed character data as will.
DTD ATTRIBUTES
DECLARING ATTRIBUTES:
XML element attributes are declared with an ATTLIST Declaration.An Attribute declaration has the
following syntax
<! AttList element_name attribute_name attribute- type default- value>
It defines the element which can have the attributes the name of the attributes the type of the attribute
and the default attributes values . >
VALUE

Explanation

CDATE

The value is a character data

(eval|eval|)

The value must be an enumerated value

ID

The value is a unique ID

IDREF

The value is the ID of another element

IDREFS

The Value is a list of other IDs

NMTOKEN

The value is a list of valid XML names.

Entity

The values is an entity .

Entities

The values is a list of entities.

Notation

The value is a name of a notation .

XML

The value is predefined .

XHTML Modularization.
The XHTML modularization-model defines the modules of XHTML.
Why XHTML Modularization?
XHTML contains most of the functionality a web developer will need.
71

For some purposes XHTML is too large and complex, and for other purposes it's too simple.
By splitting XHTML into modules, the W3C (World Wide web Consortium) has created small and welldefined sets of XHTML elements that can be used separately for small devices, or combined with other
XML standards in more complex applications.
With modular XHTML, designers can:
Choose the elements to be supported by a device
Simplify XHTML for small devices
Extend XHTML for complex applications by adding new XML functionality (like MathML, SVG, Voice
and Multimedia)
Define XHTML profiles like XHTML Basic (a subset of XHTML for mobile devices)
XHTML Modules
W3C has split the definition of XHTML into 28 modules:
Module name

Description

Applet Module Defines the deprecated* applet element


Base Module

Defines the base element

Basic Forms Module

Defines the basic forms elements

Basic Tables Module

Defines the basic table elements

Bi-directional Text Module

Defines the bdo element

Client Image Map Module

Defines browser side image map elements

Edit Module

Defines the editing elements del and ins

Forms Module Defines all elements used in forms


Frames Module Defines the frameset elements
Hypertext Module

Defines the a element

Iframe Module Defines the iframe element


Image Module Defines the img element
Intrinsic Events Module Defines event attributes like onblur and onchange
Legacy Module Defines deprecated* elements and attributes
Link Module

Defines the link element

List Module

Defines the list elements ol, li, ul, dd, dt, and dl

Metainformation Module

Defines the meta element

Name Identification Module

Defines the deprecated* name attribute

Object Module Defines the object and param elements


Presentation Module

Defines presentation elements like b and i

Scripting Module

Defines the script and nonscript elements

Server Image Map Module


Structure Module

Defines server side image map elements

Defines the elements html, head, title and body

Style Attribute Module Defines the style attribute


72

Style Sheet Module

Defines the style element

Tables Module Defines the elements used in tables


Target Module Defines the target attribute
Text Module

Defines text container elements like p and h1

XML Documents Form a Tree Structure


All elements can have text content and attributes (just like in HTML).
Example:
The image above represents one book in the XML below:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
The root element in the example is <bookstore>. All <book> elements in the document are contained
within <bookstore>.
73

The <book> element has 4 children: <title>,< author>, <year>, <price>.


12.

Displaying XML with CSS

With CSS (Cascading Style Sheets) you can add display information to an XML document.
Displaying your XML Files with CSS?
It is possible to use CSS to format an XML document.
Below is an example of how to use a CSS style sheet to format an XML document:
Below is a fraction of the XML file. The second line links the XML file to the CSS file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/css" href="cd_catalog.css"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
.
.
.
</CATALOG>
13.

Displaying XML with XSLT

With XSLT you can transform an XML document into HTML.


Displaying XML with XSLT
74

XSLT is the recommended style sheet language of XML.


XSLT (eXtensible Stylesheet Language Transformations) is far more sophisticated than CSS.
XSLT can be used to transform XML into HTML, before it is displayed by a browser:
Display XML with XSLT
Transforming XML with XSLT on the Server
In the example above, the XSLT transformation is done by the browser, when the browser reads the XML
file.
Different browsers may produce different result when transforming XML with XSLT. To reduce this
problem the XSLT transformation can be done on the server.
****************
ALL The BEST

75

You might also like