KEMBAR78
Web Tech | PDF | Html | Html Element
0% found this document useful (0 votes)
62 views110 pages

Web Tech

Uploaded by

sathya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views110 pages

Web Tech

Uploaded by

sathya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

UNIT - I

HTML Introduction:
HTML, or Hyper Text Markup Language, is the standard markup language
used to create web pages. It’s a combination of Hypertext, which defines the link
between web pages, and Markup language, which is used to define the text
document within tags to structure web pages. This language is used to annotate
text so that machines can understand and manipulate it accordingly. HTML is
human-readable and uses tags to define what manipulation has to be done on the
text.
What is HTML?
HTML stands for HyperText Markup Language and it is used to create
webpages. It uses HTML tags and attributes to describe the structure and
formatting of a web page.
HTML consists of various elements, that are responsible for telling search
engines how to display page content. For example, headings, lists, images, links,
and more.
HTML Example
HTML
<!DOCTYPE html>
<html>
<head>
<title>First HTML Code</title>
</head>
<body>
<h2>Hello World</h2>
<p>Hypertext Markup Language</p>
</body>
</html>
Features of HTML
 It is easy to learn and easy to use.
 It is platform-independent.
 Images, videos, and audio can be added to a web page.
 Hypertext can be added to the text.
 It is a markup language.
HTML Elements and Tags
HTML uses predefined tags and elements that instruct the browser on how
to display the content. HTML elements include an opening tag, some content, and
a closing tag. It’s important to remember to include closing tags. If omitted, the
browser applies the effect of the opening tag until the end of the page.
This section will dive into the basic structure of an HTML page, which includes
essential building-block elements like doctype declaration, HTML, head, title, and
body elements.

HTML Page Structure


The basic structure of an HTML page is shown below. It contains the essential
building-block elements (i.e. doctype declaration, HTML, head, title, and body
elements) upon which all web pages are created.
 <!DOCTYPE html> – This is the document type declaration (not technically a
tag). It declares a document as being an HTML document. The doctype
declaration is not case-sensitive.
 <html> – This is called the HTML root element. All other elements are
contained within it.
 <head> – The head tag contains the “behind the scenes” elements for a
webpage. Elements within the head aren’t visible on the front end of a
webpage. HTML elements used inside the <head> element include:
 <style> – This HTML tag allows us to insert styling into our web pages and
make them appealing to look at with the help of CSS.
 <title> – The title is what is displayed on the top of your browser when you
visit a website and contains the title of the webpage that you are viewing.
 <base> – It specifies the base URL for all relative URL’s in a document.
 <noscript> – Defines a section of HTML that is inserted when the scripting has
been turned off in the user’s browser.
 <script> – This tag is used to add functionality to the website with the help of
JavaScript.
 <meta> – This tag encloses the metadata of the website that must be loaded
every time the website is visited. For eg:- the metadata charset allows you to
use the standard UTF-8 encoding on your website. This in turn allows the users
to view your webpage in the language of their choice. It is a self-closing tag.
 <link> – The ‘link’ tag is used to tie together HTML, CSS, and JavaScript. It is
self-closing.
 <body> – The body tag is used to enclose all the visible content of a webpage.
In other words, the body content is what the browser will show on the front
end.
HTML History
HTML is a markup language used by the browser to manipulate text,
images, and other content, in order to display it in the required format. HTML
was created by Tim Berners-Lee in 1991. The first-ever version of HTML
was HTML 1.0, but the first standard version was HTML 2.0, published in 1995.
Currently, we are using HTML5, which is the latest and most recent version of
HTML.
Advantages of HTML
 HTML is used to build websites.
 It is supported by all browsers.
 It can be integrated with other languages like CSS, JavaScript, etc.
Disadvantages of HTML
 HTML can only create static web pages. For dynamic web pages, other
languages have to be used.
 A large amount of code has to be written to create a simple web page.
 The security feature is not good.

SGML:
SGML stands for Standard generalized markup language is a Standard
generalized markup language that makes use of a superset of extensively used
markup languages like HTML and XML. It is used for marking up files and has the
gain of now no longer depending on a particular application.
It is basically derived from GML (Generalized Markup Language), which allowed
users to work on standardized formatting styles for electronic documents. It was
developed and standardized by the International Organization for
Standards (ISO) in 1986. SGML specifies the rules for tagging elements. These tags
can then be interpreted to layout factors in specific ways.
It is used extensively to manipulate massive files which are a concern with
common revisions and want to be published in one-of-a-kind formats due to the
fact it’s far a massive and complicated system, it isn’t always but extensively used
on private computers.
Components of SGML:
 SGML provides a way of describing the relationships between these entities,
elements, and attributes, and tells the computer how it can recognize the
component parts of a document and it is based on the concept of a document
being composed of a series of entities (object).
 It provides rules that allow the computer to recognize where the various
elements of a text entity start and end.
 Document Type Definition (DTD) in SGML is used to describe each element of
the document in a form that the computer can understand.
SGML is the simplest medium to produce files that can be read by people and
exchanged between machines and applications in a straightforward manner. It is
easy to understand by the human as well as the machine.
Features of SGML
 The SGML has an entity system that provides the feature of reusability of the
content pieces.
 It provides the feature for the user to create their own markup language and
document formats.
Example: In this example, we will write a code in a structured document
represented in an SGML-like format.

<EMAIL>
<RECEIVER>
<PERSON>
<FIRSTNAME>Alice</FIRSTNAME>
</PERSON>
</RECEIVER>
<BODY>
<p>This is a sample paragraph for demonstrating
SGML Example. The receiver's first name is
included in the content.</p>
</BODY>
</EMAIL>

Output:

SGML Example Output


Advantages
 Flexibility: SGML’s ability to be customized to certain document types and
sectors enables the development of markup languages.
 Rich Metadata: SGML has strong metadata features, making it appropriate for
applications involving structured data and document management.
 Reusability: The entity system in SGML makes it possible to reuse content
pieces, which enhances document consistency and maintenance.
Disadvantages
 Complexity: SGML requires a deeper comprehension of markup language
concepts than HTML and is more challenging to master.
 Lack of Widespread Browser Support: SGML’s utility in web development is
constrained since, unlike HTML, it is not natively supported by web browsers.
 Implementation Overhead: Creating and maintaining SGML DTDs can take a
lot of effort and resources.
HTML Head
The HTML <head> element is used as a container for metadata (data about
data). It is used between <html> tag and <body> tag.
The head of an HTML document is a part whose content is not displayed in
the browser on page loading. It just contains metadata about the HTML document
which specifies data about the HTML document.
An HTML head can contain lots of metadata information or can have very
less or no information, it depends on our requirement. But head part has a crucial
role an HTML document while creating a website.
<head>
<!-- head content goes here -->
</head>
Metadata defines the document title, character set, styles, links, scripts, and other
meta information.
Following is a list of tags used in metadata:
o <title>
o <style>
o <meta>
o <link>
o <script>
o <base>
HTML <title> Element
The HTML <title> element is used to define the title of the document. It is used in
all HTML/XHTML documents. The <title> element must be placed between <head>
element, and one document can only have one title element.
What does <title> element do?
1. It defines a title in the browser tab.
2. It provides a title for the page when it is added to favourites.
3. It displays a title for the page in search engine results.
HTML <style> Element
The HTML <style> element is used to style the HTML page. The <style>
element can have CSS properties for that HTML page only. If we want to apply CSS
for multiple pages then we should use separate CSS file.
HTML <link> Element
The HTML <link> element is used to link an external style sheet to your
webpage. The <link> element contains main two attributes which are "rel" and
"href". The rel attribute indicates that it is a stylesheet, and href gives the path to
that external file.
HTML <meta> Element
The HTML <meta> element is used to specify the character set, page
description, keywords, authors and other metadata on the webpage.
Metadata is mainly used by browsers, search engines, and other web services to
rank your webpage better.
The charset attribute specifies the character encoding. In this example we
have set it to "UTF-8" which means it can handle to display any language.
HTML <base> Element
The HTML <base> element is used to specify the base URL and base target
for all relative URLs in a page.
HTML <script> element
HTML <script> element is used to apply client side JavaScript for the same
page or to add an external JavaScript file to current page.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Awesome Website</title>
<meta name="description" content="Welcome to my awesome website!">
<meta name="keywords" content="awesome, website, cool, amazing">
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- The rest of the page content goes here -->
</body>
</html>
HTML <body> tag
HTML <body> tag defines the main content of an HTML document which
displays on the browser. It can contain text content, paragraphs, headings, images,
tables, links, videos, etc.
The <body> must be the second element after the <head> tag or it should be
placed between </head> and </html> tags. This tag is required for every HTML
document and should only use once in the whole HTML document.
Syntax
<body> Place your Content here........</body>

Attribute Value Description

alink color It defines the color of the active link in a document. (Not
supported in HTML5)

background URL It determines the background image for the document. (Not
supported in HTML5)

bgcolor color It determines the background color of the content. (Not


supported in HTML5)

link color It determines the color of the unvisited link. (Not supported in
HTML5)

text color It determines the color of the text in the document. (Not
supported in HTML5)

vlink color It determines the color of the visited link. (Not supported in
HTML5)

onload Function call on page loading


onunload Function call when user leaves the page

onfocus Function call when document receives focus by user.

onblur Function call when document loses focus by user.

<!DOCTYPE html>
<html>
<head>
<title>Body Tag</title>
</head>
<body>
<h2>Example of body tag</h2>
<p>This paragraph is written between the body tag</p>
</body>
</html>

HTML Form
An HTML form is a section of a document which contains controls such as text
fields, password fields, checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the server
for processing such as name, email address, password, phone number, etc. .

Why use HTML Form


HTML forms are required if you want to collect some data from of the site
visitor.
For example: If a user want to purchase some items on internet, he/she must
fill the form such as shipping address and credit/debit card details so that item can
be sent to the given address.

HTML Form Syntax


<form action="server url" method="get|post">
//input controls e.g. textfield, textarea, radiobutton, button
</form>
HTML Form Tags
Let's see the list of HTML 5 form tags.

Tag Description

<form> It defines an HTML form to enter inputs by the used side.

<input> It defines an input control.

<textarea> It defines a multi-line input control.

<label> It defines a label for an input element.

<fieldset> It groups the related element in a form.

<legend> It defines a caption for a <fieldset> element.

<select> It defines a drop-down list.

<optgroup> It defines a group of related options in a drop-down list.

<option> It defines an option in a drop-down list.

<button> It defines a clickable button.

HTML 5 Form Tags


Let's see the list of HTML 5 form tags.

Tag Description

<datalist> It specifies a list of pre-defined options for input control.

<keygen> It defines a key-pair generator field for forms.

<output> It defines the result of a calculation.

HTML <form> element


The HTML <form> element provide a document section to take input from user. It
provides various interactive controls for submitting information to web server
such as text field, text area, password field, etc.
Syntax:
<form>
//Form elements
</form>

HTML <input> element


The HTML <input> element is fundamental form element. It is used to create
form fields, to take input from user. We can apply different input filed to gather
different information form user. Following is the example to show the simple text
input.
Example:
<body>
<form>
Enter your name <br>
<input type="text" name="username">
</form>
</body>

Output:

HTML TextField Control


The type="text" attribute of input tag creates textfield control also known as
single line textfield control. The name attribute is optional, but it is required for
the server side component such as JSP, ASP, PHP etc.
<form>
First Name: <input type="text" name="firstname"/> <br/>
Last Name: <input type="text" name="lastname"/> <br/>
</form>
Output:
HTML <textarea> tag in form
The <textarea> tag in HTML is used to insert multiple-line text in a form. The
size of <textarea> can be specify either using "rows" or "cols" attribute or by CSS.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<form>
Enter your address:<br>
<textarea rows="2" cols="20"></textarea>
</form>
</body>
</html>

Output:

Label Tag in Form


It is considered better to have label in form. As it makes the code
parser/browser/user friendly.
If you click on the label tag, it will focus on the text control. To do so, you
need to have for attribute in label tag that must be same as id attribute of input tag.
<form>
<label for="firstname">First Name: </label> <br/>
<input type="text" id="firstname" name="firstname"/> <br/>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname" name="lastname"/> <br/>
</form>
Output:

HTML Password Field Control


The password is not visible to the user in password field control.
<form>
<label for="password">Password: </label>
<input type="password" id="password" name="password"/> <br/>
</form>
Output:

HTML 5 Email Field Control


The email field in new in HTML 5. It validates the text for correct email
address. You must use @ and . in this field.
<form>
<label for="email">Email: </label>
<input type="email" id="email" name="email"/> <br/>
</form>
It will display in browser like below:

Radio Button Control


The radio button is used to select one option from multiple options. It is used
for selection of gender, quiz questions etc.
If you use one name for all the radio buttons, only one radio button can be selected
at a time.
Using radio buttons for multiple options, you can only choose a single option at a
time.
<form>
<label for="gender">Gender: </label>
<input type="radio" id="gender" name="gender" value="male"/>Male
<input type="radio" id="gender" name="gender" value="female"/>Female
<br/>
</form>

Checkbox Control
The checkbox control is used to check multiple options from given checkboxes.
<form>
Hobby:<br>
<input type="checkbox" id="cricket" name="cricket" value="cricket"/>
<label for="cricket">Cricket</label> <br>
<input type="checkbox" id="football" name="football" value="football"/>
<label for="football">Football</label> <br>
<input type="checkbox" id="hockey" name="hockey" value="hockey"/>
<label for="hockey">Hockey</label>
</form>
Output:
Submit button control
HTML <input type="submit"> are used to add a submit button on web page.
When user clicks on submit button, then form get submit to the server.
Syntax:
<input type="submit" value="submit">
The type = submit , specifying that it is a submit button
The value attribute can be anything which we write on button on web page.
The name attribute can be omit here.
Example:
<form>
<label for="name">Enter name</label><br>
<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</form>
Output:

HTML <fieldset> element:


The <fieldset> element in HTML is used to group the related information of a form.
This element is used with <legend> element which provide caption for the grouped
elements.
Example:
<form>
<fieldset>
<legend>User Information:</legend>
<label for="name">Enter name</label><br>
<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</fieldset>
<form>
Output:

HTML Form Example


Following is the example for a simple form of registration.
<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<h2>Registration form</h2>
<form>
<fieldset>
<legend>User personal information</legend>
<label>Enter your full name</label><br>
<input type="text" name="name"><br>
<label>Enter your email</label><br>
<input type="email" name="email"><br>
<label>Enter your password</label><br>
<input type="password" name="pass"><br>
<label>confirm your password</label><br>
<input type="password" name="pass"><br>
<br><label>Enter your gender</label><br>
<input type="radio" id="gender" name="gender" value="male"/>Male <br>
<input type="radio" id="gender" name="gender" value="female"/>Female
<br/>
<input type="radio" id="gender" name="gender" value="others"/>others <
br/>
<br>Enter your Address:<br>
<textarea></textarea><br>
<input type="submit" value="sign-up">
</fieldset>
</form>
</body>
</html>
Output:
UNIT – II
JavaScript:
JavaScript is the most powerful and versatile web programming language. It
is used for making the websites interactive. JavaScript helps us add features like
animations, interactive forms and dynamic content to web pages.
What is JavaScript?
JavaScript is a programming language used for creating dynamic content
on websites. It is a lightweight, cross-platform and single-threaded programming
language. JavaScript is an interpreted language that executes code line by line
providing more flexibility. It is a commonly used programming language to create
dynamic and interactive elements in web applications. It is easy to learn.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
Displaying clocks etc.
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>

Output:
Welcome to JavaScript
Hello JavaScript by JavaScript

Language elements
By tradition, the first example program shown for computer languages is
one called 'Hello World', which simply writes the message 'hello world' to some
type of output; it is the simplest thing that shows a program/computer is working.
Figure 1 shows the source of a simple web page which contains a JavaScript 'hello
world' program.
<html>
<head>
<title>A simple web page</title>
<script type="text/javascript">
alert("Hello world!");
</script>
</head>
<body>
Page body text
</body>
</html>

We'll consider later on the way in which this code is embedded in the web
page, and look first at the fundamentals of the language. The 'hello world' program
consists of the single line: alert("Hello world!");, all the rest of the code is the HTML
page that contains that short program.
Code layout and format
Case sensitivity:
JavaScript is a case sensitive language. Our 'hello world' program used the
function alert(); if we'd written it as 'ALERT()', or 'Alert()', the program would not
have worked, as the function would not have been recognised. Similarly, when we
come to use variables, it is important to note that 'x' and 'X' are different variables.
Whitespace
JavaScript largely ignores extra whitespace (spaces, tabs, line breaks),
which means that you can format you code with whatever pattern of spacing and
indentation that you like. Clear spacing and indentation can help to make the code
more readable and make the purpose clear. Note, however, that developers will
quite often compress entire libraries onto one line, in part to obfuscate how code
works (by its very nature, JavaScript code will usually be publicly available), and in
part to remove extra characters and shrink file sizes. This is definitely not
recommended practice, and for this course we expect all code to be clearly laid out.
Line terminators
All statements (roughly speaking, the same thing as 'a line of code') should
be ended with the semicolon character ';', as in our example above. As noted in the
introduction, JavaScript was designed to be forgiving, and one example of this is
that line terminators can be omitted; however it is considered sloppy practice to
do this, and it is possible to write ambiguous code if you rely on JavaScript to 'do
the right thing' when you leave line endings out.
Comments
All programs - whatever language they are written in – should contains
comments. Comments are messages to a human reader that explain what is going
on in the program. JavaScript recognises a number of different comment styles.
Single line comments start with '//' – anything after that will be ignored. Longer
multi-line comments can be placed between the opening characters '/*' and the
closing characters '*/'. Examples of different comment styles are shown below.
// This is a single line comment

i = 1; // Comments can also be placed after some code

/* This is a
multi-line
comment */

/*
* People often
* format
* multi-line comments like this
*/

/* This comment uses multi-line format */


Identifiers, literals and reserved words
An identifier is a name of a data item, such as a variable, array of function,
whilst a literal is a fixed value that is not going to change (though you can obviously
change the literal associated with a variable, including those inside "object
literals"). In the second comment example above, the sample code 'i = 1;' contains
an example of a variable which has the identifier i and a literal value, 1.
There are some simple rules that govern the names that can be used for
identifiers. The first character must be an uppercase or lowercase letter, or a dollar
sign ( $ ) or the underscore character ( _ ). The remainder can be any mixture of
letters, numbers, dollar signs or underscore characters. A final restriction is that
identifiers cannot be one of the reserved words in JavaScript. Reserved words are
keywords that are used as commands and in-built functions, clearly a program that
used such terms as variable names would be very confusing. Current reserved
words are listed below, including some that have been specified in the Ecma
standard as reserved for possible future use in JavaScript. You do not need to
memorise these lists, just to be aware that reserved words exist, and that you
should choose variable names appropriately. If your code is behaving
unexpectedly, (or generally, failing to run), it may be worth checking that you have
not tried to use a reserved word as an identifier.
JavaScript reserved
words: break, case, catch, continue, default, delete, do, else, false, finally, fo
r, function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof,
var, void, while, with Ecma reserved words (for possible
futurese): abstract, boolean, byte, char, class, const, debugger, double, enum, expo
rt, extends, final, float, goto, implements, import, int, interface, long, native, ackag
e, private, protected, public, short, static, super, synchronized, throws, transient,
volatile,
Data types and values:
JavaScript supports a number of primitive (basic) types, plus more
sophisticated composite types (linking several primitives together). Primitive data
types are numbers (with no distinction between integers/whole numbers or
floating point/decimal numbers), text strings (a series of characters), and boolean
values (that can have the value either 'true' or 'false'). Composite types include
arrays – collections of primitive types – and objects – which incorporate both data
items and code that acts on those data items (see below). JavaScript includes a
number of built in specialised objects, including for example, objects representing
the browser window and the current document.
Variable declaration
New variables must be declared using the keyword 'var', for example: var
i; or var i = 1;. In the former case the variable has been created but is not yet
defined, in the latter case we have both declared it and initialised it (given it a
value).
Numbers
Numbers can be represented in various forms in JavaScript – integers,
floating point values and octal (base 8) or hexadecimal (base 16) values. Basic
operations occur as you might expect, using +, -, * and /, for example 'i = i + 1;' or 'x
= y * z;'. More advanced functions are available through the Math object; for
example 'x = Math.sqrt(y);'. Here, we are calculating x as the square root of y, using
the sqrt() method of the Math object. We will learn more about objects and
methods below.
Strings
A string is a sequence of characters – letters, digits, punctuation marks and
so on. Strings must be placed within quotes, using either single or double quote
characters.
'This is a string'
"So is this"
"Don't forget that single quotes can be used inside double quotes"
Strings can be joined using the '+' operator, for example: mesg = 'Hello ' + 'world!';
Boolean values
The Boolean data type has only two possible values: true or false. You will
most commonly come across these implicitly (i.e. they won't be named variables)
as the result of logical comparisons. Consider the code fragment:
if (x > y)
a = a + 1;
else
b = b + 1;
In the first line, we make a comparison between two values, x and y, and then
specify two alternative things for the program to do depending on their relative
values. The comparison gives a result that is either true or false; this is a Boolean
value.
Objects
An object is a composite data type that includes several named data items,
that are usually referred to as properties of the object. We can refer to the
properties of an object using the syntax object_name.property_name. Thus, if we
had an object called point, we might refer to the properties point.x and point.y.
Objects can also contain code that does specific jobs, usually associated with the
data in the object. These are called methods if associated with objects (though more
generally these code chunks are called functions). We'll come back to these in more
detail later, as there are some oddities about them that you don't see in other
languages.
Methods usually act on the properties of the object (or on data passed in as
a method parameter). We saw an example of this in the description of numbers
above: sqrt() is a method that is part of the Math object, and we passed in the
variable y for it to work on. It returned to us the result, which we put in
the x variable:
x = Math.sqrt(y);
Methods are access in the same manner as properties, using the
syntax object_name.method_name() (note the parentheses to denote a method
rather than a variable, and to allow data to be passed in).
The properties of an object can be data items, methods/functions, or other
object types. The fact that an object property can itself be an object means that you
will see pieces of JavaScript code with multiple full stops ("chaining"), like this:
document.myform.button
Here, we are referring to button, which is a property of the object myform,
which in turn is a property of the object document. Equally, we can throw in method
calls, like this:
document.mymethod().buttonClick()
i.e. run document.mymethod(), and whatever comes back from that method
call, call its buttonClick method. Such chaining is very common in scripting
languages, because it is easy to cut and paste without understanding and it avoids
accidentally leaving out chunks of code. It is more concise than:
var a = document;
b = a.mymethod();
c = b.buttonClick();
and creates less unnecessary variables (and is therefore more efficient).
However, on the negative side, if something doesn't work, it is often hard to tell
where it is failing, and you may need to expand the code like the above to find the
error in a specific line.
Objects have to be made using the new operator, like this:
var i = new Object();
var myDate = new Date();
Here, i is being declared as a new generic object, to which we can attach
properties and methods, whilst myDate is being declared as an instance of the
specialised built in object Date..
Arrays
A regular array is a specialised object which contains a set of data values
which can be referred to by index values, starting at 0. This if we have an array x,
then x[0] refers to the first value in the array, x[1] to the second value, and so on.
As they are objects, arrays are also declared using the new operator:
var myArray = new Array(); // declares an empty array
var myOtherArray = new Array(3,5,7); // an array declared and initialised with
three values
var countries = new Array('England,'Scotland,'Wales'); // an array with text items
We can also declare arrays using a special array notation:
var myArray = []; // creates a new array
var myOtherArray = [0,'x',true] // creates and initialises an array containing
different data types.
Arrays can contain any data types, including other arrays, thus we can create
matrices like this:
var myMatrix = [ [1,2,3], [4,5,6], [7,8,9] ];
Here, we have created an array called myMatrix, using the [] notation. It
contains three elements, each of which is an array, again declared using the array
notation. We can refer to elements of this matrix, for
example myMatrix[1][2] refers to the third element (since we start counting at
zero!) of the second value (the array [4,5,6]) in myMatrix.
Since arrays are specialised objects, they can have methods as well as the
value properties. The Array() object is a specially defined object, that has a number
of built in methods and properties, including 'sort()' and 'length'. The
property length indicates how many elements the array has, and will change as
more elements are added to the array. The method sort, as you might expect, sorts
the array. (Something that is less obvious is that by default 'sort()' uses dictionary
order sorting, even if the values are all numbers. However, alternate sorting
functions can be provided). Whereas the length property returns a value when
inspected, the sort() method acts on the data in the array. Thus, we can use them
like this:
x = y.length; // sets x to the current value of the length property of an array y
y.sort(); // modifies array y by sorting its elements
Functions
Most modern languages are procedural, that is, they are structured into
procedures (in Java, methods; Python, functions): useful chunks of code that can
be called to do a job, before the code execution returns to the calling point. In
JavaScript, these structures are called functions (though in objects, when named,
you may find them called methods &ndash see above). An unusual aspect of
JavaScript is that functions can be considered akin to variables in most contexts, so
we can attach variable names to functions, as we do, for example, in:
<BODY onload="initialize()">
This extends to treating functions like variables more generally, so, for example,
you can hold a function in an array, or pass it into another function.
Functions are defined using the function keyword and return results to the calling
code using return. The code below shows a simple function.
function square(x) {
return x*x;
}
This creates a function called square, which will return the square of its
input parameter. We would use it like this:
i = square(4); // sets i to the square of 4, i.e. 16
x = square(y); // sets x to the square of the current value of y.
a = square(b+c); // b+c will be calculated first, and then the function will be called.
This code also illustrates an important part of the syntax of JavaScript (and
all C-like languages), that the curly brackets '{}' are used to group together a series
of statements. In this example the function consists of only one line; most functions
are more complex and require several (possibly many) lines, and the brackets
indicate where the function code starts and ends.
One final thing on functions; note that occasionally we want to set up a
function without a name. The syntax for this is:
function () {
// stuff done
}
This may seem strange, but it allows us to do stuff like this:
var f = function () {
// stuff done
}
or
someFunction(function () {
// stuff done in function passed as a parameter
})
Operators
The examples above have a contained a few examples of operators, tokens
in the code which make the program do some sort of operation on data items. Thus,
we have seen that number data types can be manipulated with the basic arithmetic
operators +, -, * and /. There are many other operators in JavaScript; we have
already seen the 'new' and '.' operators that are used with objects, and the '[]'
operator that is used with arrays. It is beyond the scope of this introduction to go
through all operators in turn, but it is important to introduce a few commonly used
ones.
Two of the most commonly used – and most commonly confused – operators
are the assignment operator '=' and the test for equality '=='. The assignment
operator is used when we assign a value to variables.
a = 1;
mesg = 'Hello';
x = y;
The test for equality is used in comparisons – usually in 'if' statements – to
check whether two values are the same, for example:
if (x==y)
a = a + 1;
else
b = b + 1;
A very easy mistake is to write the first line in this fragment as 'if (x=y)'. After
all, this makes sense in English and maths. This is not necessarily a bug – it is valid
code – although it is almost never what you intended. As '=' is the assignment
operator, this expression would first set x to be equal to the current value of y. The
operator would then return a value of 'true', indicating that it had successfully
carried out the assignment operation. The true state would then cause the 'if'
statement to be validly interpreted, and the first alternative action would be taken.
A final pair of operators that should be mentioned in any brief introduction
are '++' and '--'. These are special unary operators (meaning, they act on a single
item) which increment or decrement a variable by one. You will see them
commonly used, especially in loop counters:
i++; // increases the value of i by 1;
j--; // decreases the value of j by 1
Variable scope
So far, this introduction has covered lexical issues (rules for the format of
the program and what characters and terms can be used), and data types. The final
part of this section discusses variable scope. The scope of a variable indicates the
different parts of a program in which its value is defined. Variables defined within
a function are local to that function, and thus have no meaning when we leave the
function to return to the rest of the code. By contrast, a variable defined in the main
body of the program is termed a global variable. As the name suggests global
variables are defined throughout the program, and thus functions can 'see' the
values of global variables. The code below illustrates this.
// A function
function circleArea(j) {
var i; // local scope
i = pi * (j * 2);
return i;
}
// Main program
var pi = 3.14; // global scope
var radius;
var area;

radius = 5;
area = circleArea(radius);
document.write("Radius:" + radius + " Area:" + area);
The program uses a function to calculate the area of a circle. It illustrates a
number of features. We have used the variables i and j in the function. j takes the
value of 'radius' that is passed in by the main program. The function calculates the
answer as i. The variable pi was defined in the main program and thus has global
scope; it can therefore be used in the function. The variable i is defined within the
function, and has local scope; we cannot see the value of this once we return to the
main program; instead we set the variable area to the value returned by the
function. In fact, we could have used different variables called radius and area in
our function as well as in the main program.
If a function has local variables (declared using the var statement) that have
the same name as global variables, they will take precedence in the function. When
we return to the main program, we return to our original versions of the variables,
which will have retained their values, regardless of what might have happened in
the function. In contrast, if we refer to a variable without declaring it in the
function, we'll use (and possibly modify) the global variable of that name. Clearly,
it is fairly easy to make mistakes with scope, and to unintentionally over-write the
original value of global variables.
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to
get the object. But, we direct create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.
By object literal
By creating instance of Object directly (using new keyword)
By using an object constructor (using new keyword)
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
Let’s see the simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output:
102 Shyam Kumar 40000

2) By creating instance of Object


The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Let’s see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
101 Ravi 50000

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
The this keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>

Output of the above example


103 Vimal Jaiswal 30000

JavaScript Array
JavaScript array is an object that represents a collection of similar type of
elements.
There are 3 ways to construct array in JavaScript
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)

1) JavaScript array literal


The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
The .length property returns the length of an array.
Output of the above example
Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output of the above example
Arun
Varun
John

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

Output of the above example


Jai
Vijay
Smith
UNIT – III
VB Script: Introduction:
The VBScript stands for Visual Basics Script language. Basically it is the
combination of Visual Basic programming language and JavaScript language.
VBScript was invented and maintained by Microsoft. It is used to develop dynamic
web pages. It is much lighter compared to Visual Basic programming language but
works as a scripting language like JavaScript. To run VBScript on the client-side,
the client must have to use Internet Explorer because other browsers are still not
supported by the VBScript.
Note: All the VBScript editors are actually HTML editors that supports
VBScript. Setup for VBScript:
Step 1: Open your text editor and create a basic HTML file (for example:
index.html) and paste the below code inside that file.
html

<!DOCTYPE html>
<html>
<head>
<title>VBScript Introduction</title>
</head>
<body>
<!-- Paste VBScript Here -->
</body>
</html>

Step 2: Paste the below code inside the body tag of your HTML code, or you
can paste it inside the head tag. Exactly the same as you have done with
JavaScript.
javascript

document.write("Hello geeks, greeting from GeeksforGeeks")

Step 3: Combine both the code and run it on Microsoft Edge and you will get
the below output in the console.
html

<!DOCTYPE html>
<html>
<head>
<title>VBScript Introduction</title>
</head>
<body>
<script type="text/vbscript">
document.write("Welcome to GeeksforGeeks")
</script>
</body>
</html>

Output:
Welcome to GeeksforGeeks
VBScript Placement in HTML File
There is a flexibility given to include VBScript code anywhere in an HTML
document. But the most preferred way to include VBScript in your HTML file is as
follows −
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can put VBScript in different ways −
VBScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows −
<html>
<head>
<script type = "text/Vbscript">
<!--
Function sayHello()
Msgbox("Hello World")
End Function
//-->
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
It will produce the following result − A button with the name SayHello. Upon
clicking on the Button, the message box is displayed to the user with the message
"Hello World".

VBScript in <body>...</body> section


If you need a script to run as the page loads so that the script generates
content in the page, the script goes in the <body> portion of the document. In this
case, you would not have any function defined using VBScript −
<html>
<head> </head>
<body>
<script type = "text/vbscript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
This will produce the following result −
Hello World
This is web page body
VBScript in <body> and <head> sections
You can put your VBScript code in <head> and <body> section altogether as
follows −
<html>
<head>
<script type = "text/vbscript">
<!--
Function sayHello()
msgbox("Hello World")
End Function
//-->
</script>
</head>
<body>
<script type = "text/vbscript">
<!--
document.write("Hello World")
//-->
</script>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
It will produce the following result − Hello World message with a 'Say Hello'
button. Upon Clicking on the button a message box with a message "Hello World" is
displayed to the user.
Hello World
VBScript in External File
As you begin to work more extensively with VBScript, you will likely find that
there are cases, where you are reusing identical VBScript code on multiple pages
of a site. You are not restricted to be maintaining identical code in multiple HTML
files.
The script tag provides a mechanism to allow you to store VBScript in an
external file and then include it into your HTML files. Here is an example to show
how you can include an external VBScript file in your HTML code using script tag
and its src attribute −
<html>
<head>
<script type = "text/vbscript" src = "filename.vbs" ></script>
</head>
<body>
.......
</body>
</html>
To use VBScript from an external file source, you need to write your all VBScript
source code in a simple text file with extension ".vbs" and then include that file as
shown above. For example, you can keep the following content in filename.vbs file
and then you can use sayHello function in your HTML file after including
filename.vbs file.
Function sayHello()
Msgbox "Hello World"
End Function

VBScript Variables
A variable is a named memory location used to hold a value that can be
changed during the script execution. VBScript has only ONE fundamental data
type, Variant.
Rules for Declaring Variables −
Variable Name must begin with an alphabet.
Variable names cannot exceed 255 characters.
Variables Should NOT contain a period (.)
Variable Names should be unique in the declared context.
Declaring Variables
Variables are declared using “dim” keyword. Since there is only ONE
fundamental data type, all the declared variables are variant by default. Hence, a
user NEED NOT mention the type of data during declaration.
Example 1 − In this Example, IntValue can be used as a String, Integer or even
arrays.
Dim Var
Example 2 − Two or more declarations are separated by comma(,)
Dim Variable1,Variable2
Assigning Values to the Variables
Values are assigned similar to an algebraic expression. The variable name
on the left hand side followed by an equal to (=) symbol and then its value on the
right hand side.
Rules
The numeric values should be declared without double quotes.
The String values should be enclosed within double quotes(")
Date and Time variables should be enclosed within hash symbol(#)
Examples
' Below Example, The value 25 is assigned to the variable.
Value1 = 25
' A String Value ‘VBScript’ is assigned to the variable StrValue.
StrValue = “VBScript”

' The date 01/01/2020 is assigned to the variable DToday.


Date1 = #01/01/2020#

' A Specific Time Stamp is assigned to a variable in the below example.


Time1 = #12:30:44 PM#
Scope of the Variables
Variables can be declared using the following statements that determines
the scope of the variable. The scope of the variable plays a crucial role when used
within a procedure or classes.
Dim
Public
Private
Dim
Variables declared using “Dim” keyword at a Procedure level are available
only within the same procedure. Variables declared using “Dim” Keyword at script
level are available to all the procedures within the same script.
Example − In the below example, the value of Var1 and Var2 are declared at
script level while Var3 is declared at procedure level.
Note − The scope of this chapter is to understand Variables. Functions would
be dealt in detail in the upcoming chapters.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim Var1
Dim Var2

Call add()
Function add()
Var1 = 10
Var2 = 15
Dim Var3
Var3 = Var1 + Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1 ' Displays 10 as Var1 is declared at Script level
Msgbox Var2 ' Displays 15 as Var2 is declared at Script level
Msgbox Var3 ' Var3 has No Scope outside the procedure. Prints Empty
</script>
</body>
</html>
Public
Variables declared using "Public" Keyword are available to all the
procedures across all the associated scripts. When declaring a variable of type
"public", Dim keyword is replaced by "Public".
Example − In the following example, Var1 and Var2 are available at script
level while Var3 is available across the associated scripts and procedures as it is
declared as Public.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim Var1
Dim Var2
Public Var3
Call add()
Function add()
Var1 = 10
Var2 = 15
Var3 = Var1+Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1 ' Displays 10 as Var1 is declared at Script level
Msgbox Var2 ' Displays 15 as Var2 is declared at Script level
Msgbox Var3 ' Displays 25 as Var3 is declared as Public
</script>
</body>
</html>
Private
Variables that are declared as "Private" have scope only within that script in
which they are declared. When declaring a variable of type "Private", Dim keyword
is replaced by "Private".
Example − In the following example, Var1 and Var2 are available at Script
Level. Var3 is declared as Private and it is available only for this particular script.
Use of "Private" Variables is more pronounced within the Class.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim Var1
Dim Var2
Private Var3
Call add()
Function add()
Var1 = 10
Var2 = 15
Var3 = Var1+Var2
Msgbox Var3 'Displays the sum of two values.
End Function
Msgbox Var1 ' Displays 10 as Var1 is declared at Script level
Msgbox Var2 ' Displays 15 as Var2 is declared at Script level
Msgbox Var3 ' Displays 25 but Var3 is available only for this script.
</script>
</body>
</html>

VBScript - Operators
What is an operator?
Let’s take an expression 4 + 5 is equal to 9. Here, 4 and 5 are
called operands and + is called the operator. VBScript language supports following
types of operators −
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Concatenation Operators
The Arithmetic Operators
VBScript supports the following arithmetic operators −
Assume variable A holds 5 and variable B holds 10, then −
Show Examples

Operator Description Example

+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give -5

* Multiply both operands A * B will give 50

/ Divide numerator by denumerator B / A will give 2

Modulus Operator and remainder of after an


% B MOD A will give 0
integer division

B ^ A will give
^ Exponentiation Operator
100000

The Comparison Operators


There are following comparison operators supported by VBScript language
Assume variable A holds 10 and variable B holds 20, then −
Show Examples

Operator Description Example

Checks if the value of two operands are equal


= (A == B) is False.
or not, if yes then condition becomes true.

Checks if the value of two operands are equal


<> or not, if values are not equal then condition (A <> B) is True.
becomes true.

Checks if the value of left operand is greater


> than the value of right operand, if yes then (A > B) is False.
condition becomes true.
Checks if the value of left operand is less than
< the value of right operand, if yes then (A < B) is True.
condition becomes true.

Checks if the value of left operand is greater


>= than or equal to the value of right operand, if (A >= B) is False.
yes then condition becomes true.

Checks if the value of left operand is less than


<= or equal to the value of right operand, if yes (A <= B) is True.
then condition becomes true.

The Logical Operators


There are following logical operators supported by VBScript language −
Assume variable A holds 10 and variable B holds 0, then −
Show Examples

Operator Description Example

Called Logical AND operator. If both the


AND conditions are True, then Expression a<>0 AND b<>0 is False.
becomes True.

Called Logical OR Operator. If any of the


OR two conditions is True, then condition a<>0 OR b<>0 is true.
becomes True.

Called Logical NOT Operator. It reverses


the logical state of its operand. If a
NOT NOT(a<>0 OR b<>0) is false.
condition is True, then the Logical NOT
operator will make it False.

Called Logical Exclusion. It is the


combination of NOT and OR Operator. If
XOR (a<>0 XOR b<>0) is true.
one, and only one, of the expressions
evaluates to True, result is True.

The Concatenation Operators


There are following Concatenation operators supported by VBScript
language −
Assume variable A holds 5 and variable B holds 10 then −
Show Examples

Operator Description Example


+ Adds two Values as Variable Values are Numeric A + B will give 15

& Concatenates two Values A & B will give 510

Assume variable A = "Microsoft" and variable B="VBScript", then −

Operator Description Example

+ Concatenates two Values A + B will give MicrosoftVBScript

& Concatenates two Values A & B will give MicrosoftVBScript

VBScript - Procedures

What is a Function?
A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing same code over and over again. This
will enable programmers to divide a big program into a number of small and
manageable functions. Apart from inbuilt Functions, VBScript allows us to write
user-defined functions as well. This section will explain you how to write your own
functions in VBScript.
Function Definition
Before we use a function, we need to define that particular function. The
most common way to define a function in VBScript is by using the Function
keyword, followed by a unique function name and it may or may not carry a list of
parameters and a statement with an End Function keyword, which indicates the
end of the function.
The basic syntax is shown below −
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function Functionname(parameter-list)
statement 1
statement 2
statement 3
.......
statement n
End Function
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function sayHello()
msgbox("Hello there")
End Function
</script>
</body>
</html>
Calling a Function
To invoke a function somewhere later in the script, you would simple need
to write the name of that function with the Call keyword.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function sayHello()
msgbox("Hello there")
End Function
Call sayHello()
</script>
</body>
</html>
Function Parameters
Till now, we have seen function without a parameter, but there is a facility
to pass different parameters while calling a function. These passed parameters can
be captured inside the function and any manipulation can be done over those
parameters. The Functions are called using the Call Keyword.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function sayHello(name, age)
msgbox( name & " is " & age & " years old.")
End Function
Call sayHello("Tutorials point", 7)
</script>
</body>
</html>
Returning a Value from a Function
A VBScript function can have an optional return statement. This is required
if you want to return a value from a function. For example, you can pass two
numbers in a function and then you can expect from the function to return their
multiplication in your calling program.
NOTE − A function can return multiple values separated by comma as an
array assigned to the function name itself.
Example
This function takes two parameters and concatenates them and returns
result in the calling program. In VBScript, the values are returned from a function
using function name. In case if you want to return two or more values, then the
function name is returned with an array of values. In the calling program, the result
is stored in the result variable.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function concatenate(first, last)
Dim full
full = first & last
concatenate = full 'Returning the result to the function name itself
End Function
</script>
</body>
</html>
Now, we can call this function as follows −
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function concatenate(first, last)
Dim full
full = first & last
concatenate = full 'Returning the result to the function name itself
End Function
' Here is the usage of returning value from function.
dim result
result = concatenate("Zara", "Ali")
msgbox(result)
</script>
</body>
</html>
Sub Procedures
Sub-Procedures are similar to functions but there are few differences.
Sub-procedures DONOT Return a value while functions may or may not return a
value.
Sub-procedures Can be called without call keyword.
Sub-procedures are always enclosed within Sub and End Sub statements.
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Sub sayHello()
msgbox("Hello there")
End Sub

</script>
</body>
</html>
Calling Procedures
To invoke a Procedure somewhere later in the script, you would simply need to
write the name of that procedure with or without the Call keyword.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Sub sayHello()
msgbox("Hello there")
End Sub
sayHello()

</script>
</body>
</html>

Conditional Statements
Conditional statements are used to perform different actions for different
decisions.
In VBScript we have four conditional statements:
If statement - executes a set of code when a condition is true
If...Then...Else statement - select one of two sets of lines to execute
If...Then...ElseIf statement - select one of many sets of lines to execute
Select Case statement - select one of many sets of lines to execute
VBScript If Statement
An If statement consists of a Boolean expression followed by one or more
statements. If the condition is said to be True, the statements under If condition(s)
are Executed. If the Condition is said to be False, the statements after the If loop are
executed.
Syntax
The syntax of an If statement in VBScript is −
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
End If
Flow Diagram

Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 20
Dim b : b = 10

If a > b Then
Document.write "a is Greater than b"
End If
</script>
</body>
</html>
When the above code is executed, it produces the following result −
a is Greater than b

VBScript If Else Statements


An If statement consists of a Boolean expression followed by one or more
statements. If the condition is said to be True, the statements under If condition(s)
are Executed. If the Condition is said to be False, the statements under Else Part
would be executed.
Syntax
TThe syntax of an if…else statement in VBScript is −
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
Else
Statement 1
.....
....
Statement n
End If
Flow Diagram

Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 5
Dim b : b = 25
If a > b Then
Document.write "a is Greater"
Else
Document.write "b is Greater"
End If
</script>
</body>
</html>
When the above code is executed, it produces the following result −
b is Greater

VBScript If..ElseIf..Else Statements


An If statement followed by one or more ElseIf Statements that consists of
boolean expressions and then followed by a default else statement, which executes
when all the condition becomes false.
Syntax
The syntax of an If-ElseIf-Else statement in VBScript is −
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
ElseIf (boolean_expression) Then
Statement 1
.....
....
Statement n
ElseIf (boolean_expression) Then
Statement 1
.....
....
Statement n
Else
Statement 1
.....
....
Statement n
End If
Flow Diagram
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a
a = -5
If a > 0 Then
Document.write "a is a POSITIVE Number"
ElseIf a < 0 Then
Document.write "a is a NEGATIVE Number"
Else
Document.write "a is EQUAL than ZERO"
End If
</script>
</body>
</html>
When the above code is executed, it produces the following result −
a is a NEGATIVE Number

VBScript Nested If Statement


An If or ElseIf statement inside another If or ElseIf statement(s). The Inner If
statements are executed based on the Outermost If statements. This enables
VBScript to handle complex conditions with ease.
Syntax
The syntax of a Nested if statement in VBScript is −
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
ElseIf (boolean_expression) Then
Statement 1
.....
....
Statement n
Else
Statement 1
.....
....
Statement n
End If
Else
Statement 1
.....
....
Statement n
End If
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a
a = 23
If a > 0 Then
Document.write "The Number is a POSITIVE Number"
If a = 1 Then
Document.write "The Number is Neither Prime NOR Composite"
Elseif a = 2 Then
Document.write "The Number is the Only Even Prime Number"
Elseif a = 3 Then
Document.write "The Number is the Least Odd Prime Number"
Else
Document.write "The Number is NOT 0,1,2 or 3"
End If
ElseIf a < 0 Then
Document.write "The Number is a NEGATIVE Number"
Else
Document.write "The Number is ZERO"
End If
</script>
</body>
</html>
When the above code is executed, it produces the following result −
The Number is a POSITIVE Number
The Number is NOT 0,1,2 or 3

Switch Statements in VBScript


When a user wants to execute a group of statements depending upon a value
of an expression, then he can use Select Case statements. Each value is called a Case,
and the variable being switched ON based on each case. Case Else statement is
executed if test expression doesn't match any of the Case specified by the user.
Case Else is an optional statement within Select Case, however, it is a good
programming practice to always have a Case Else statement.
Syntax
The syntax of a Select Statement in VBScript is −
Select Case expression
Case expressionlist1
statement1
statement2
....
....
statement1n
Case expressionlist2
statement1
statement2
....
....
Case expressionlistn
statement1
statement2
....
....
Case Else
elsestatement1
elsestatement2
....
....
End Select
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim MyVar
MyVar = 1
Select case MyVar
case 1
Document.write "The Number is the Least Composite Number"

case 2
Document.write "The Number is the only Even Prime Number"

case 3
Document.write "The Number is the Least Odd Prime Number"

case else
Document.write "Unknown Number"
End select
</script>
</body>
</html>
In the above example, the value of MyVar is 1. Hence, Case 1 would be executed.
The Number is the Least Composite Number

Looping Constructs:
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow more
complicated execution paths. A loop statement allows us to execute a statement or
group of statements multiple times and following is the general from of a loop
statement in VBScript.
VBScript For Loops
A for loop is a repetition control structure that allows a developer to
efficiently write a loop that needs to execute a specific number of times.
Syntax
The syntax of a for loop in VBScript is −
For counter = start To end [Step stepcount]
[statement 1]
[statement 2]
....
[statement n]
[Exit For]
[statement 11]
[statement 22]
....
[statement n]
Next
Flow Diagram
Here is the flow of control in a For Loop −
The For step is executed first. This step allows you to initialize any loop
control variables and increment the step counter variable.
Secondly, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control
jumps to the next statement just after the For Loop.
After the body of the for loop executes, the flow of control jumps to
the Next statement. This statement allows you to update any loop control variables.
It is updated based on the step counter value.
The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the For Loop terminates.
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 10
For i = 0 to a Step 2 'i is the counter variable and it is incremented by 2
document.write("The value is i is : " & i)
document.write("<br></br>")
Next
</script>
</body>
</html>
When the above code is compiled and executed, it produces the following result −
The value is i is : 0

The value is i is : 2

The value is i is : 4

The value is i is : 6

The value is i is : 8

The value is i is : 10

VBScript For...Each Loops


A For Each loop is used when we want to execute a statement or a group of
statements for each element in an array or collection.
A For Each loop is similar to For Loop; however, the loop is executed for each
element in an array or group. Hence, the step counter won't exist in this type of
loop and it is mostly used with arrays or used in context of File system objects in
order to operate recursively.
Syntax
The syntax of a For Each loop in VBScript is −
For Each element In Group
[statement 1]
[statement 2]
....
[statement n]
[Exit For]
[statement 11]
[statement 22]
Next
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
'fruits is an array
fruits = Array("apple","orange","cherries")
Dim fruitnames

'iterating using For each loop.


For each item in fruits
fruitnames = fruitnames&item&vbnewline
Next

msgbox fruitnames

</script>
</body>
</html>
When the above code is executed, it prints all the fruitnames with one item in each
line.
apple
orange
cherries

VBScript While...Wend Loop


In a While..Wend loop, if the condition is True, all statements are executed
until Wend keyword is encountered.
If the condition is false, the loop is exited and the control jumps to very next
statement after Wend keyword.
Syntax
The syntax of a While..Wend loop in VBScript is −
While condition(s)
[statements 1]
[statements 2]
...
[statements n]
Wend
Flow Diagram

Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim Counter : Counter = 10
While Counter < 15 ' Test value of Counter.
Counter = Counter + 1 ' Increment Counter.
document.write("The Current Value of the Counter is : " & Counter)
document.write("<br></br>")
Wend ' While loop exits if Counter Value becomes 15.

</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The Current Value of the Counter is : 11
The Current Value of the Counter is : 12

The Current Value of the Counter is : 13

The Current Value of the Counter is : 14

The Current Value of the Counter is : 15

VBScript Do..While statement


A Do..While loop is used when we want to repeat a set of statements as long
as the condition is true. The Condition may be checked at the beginning of the loop
or at the end of the loop.
Syntax
The syntax of a Do..While loop in VBScript is −
Do While condition
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]

Loop
Flow Diagram
Example
The below example uses Do..while loop to check the condition at the
beginning of the loop. The statements inside the loop are executed only if the
condition becomes True.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Do While i < 5
i=i+1
Document.write("The value of i is : " & i)
Document.write("<br></br>")
Loop
</script>
</body>
</html>
When the above code is executed, it prints the following output on the console.
The value of i is : 1

The value of i is : 2

The value of i is : 3
The value of i is : 4

The value of i is : 5

Do..Until Loops in VBScript


A Do..Until loop is used when we want to repeat a set of statements as long
as the condition is false. The Condition may be checked at the beginning of the loop
or at the end of loop.
Syntax
The syntax of a Do..Until loop in VBScript is −
Do Until condition
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
Loop
Flow Diagram
Example
The below example uses Do..Until loop to check the condition at the
beginning of the loop. The Statements inside the loop are executed only if the
condition is false. It exits out of the loop when the condition becomes true.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
i = 10
Do Until i>15 'Condition is False.Hence loop will be executed
i=i+1
Document.write("The value of i is : " & i)
Document.write("<br></br>")
Loop
</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The value of i is : 11
The value of i is : 12
The value of i is : 13
The value of i is : 14
The value of i is : 15
The value of i is : 16

VBScript Exit For statement


A Exit For Statement is used when we want to Exit the For Loop based on
certain criteria. When Exit For is executed, the control jumps to next statement
immediately after the For Loop.
Syntax
The syntax for Exit For Statement in VBScript is −
Exit For
Flow Diagram

Example
The below example uses Exit For. If the value of the Counter reaches 4, the
For Loop is Exited and control jumps to the next statement immediately after the
For Loop.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 10
For i = 0 to a Step 2 'i is the counter variable and it is incremented by 2
document.write("The value is i is : " & i)
document.write("<br></br>")

If i = 4 Then
i = i*10 'This is executed only if i = 4
document.write("The value is i is : " & i)
Exit For 'Exited when i = 4
End If
Next
</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The value is i is : 0
The value is i is : 2
The value is i is : 4
The value is i is : 40

VBScript Exit Do statement


An Exit Do Statement is used when we want to Exit the Do Loops based on
certain criteria. It can be used within both Do..While and Do..Until Loops.
When Exit Do is executed, the control jumps to next statement immediately
after the Do Loop.
Syntax
The syntax for Exit Do Statement in VBScript is −
Exit Do
Flow Diagram
Example
The below example uses Exit Do. If the value of the Counter reaches 10, the Do Loop
is Exited and control jumps to the next statement immediately after the For Loop.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
i=0
Do While i <= 100
If i > 10 Then
Exit Do ' Loop Exits if i>10
End If
document.write("The Value of i is : " &i)
document.write("<br></br>")
i=i+2
Loop

</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The Value of i is : 0
The Value of i is : 2
The Value of i is : 4
The Value of i is : 6
The Value of i is : 8
The Value of i is : 10

What is an Object
VBScript runtime objects help us to accomplish various tasks. This section
will help you understand how to instantiate an object and work with it.
Syntax
In order to work with objects seamlessly, we need to declare the object and
instantiate it using Set Keyword.
Dim objectname 'Declare the object name
Set objectname = CreateObject(object_type)
Example
In the below example, we are creating an object of type Scripting.Dictionary.
Dim obj
Set obj = CreateObject("Scripting.Dictionary")

Cookies:
What are Cookies?
Web Browsers and Servers use HTTP protocol to communicate and HTTP is
a stateless protocol. But for a commercial website, it is required to maintain
session information among different pages. For example, one user registration
ends after completing many pages. But how to maintain user's session information
across all the web pages. In many situations, using cookies is the most efficient
method of remembering and tracking preferences, purchases, commissions and
other information required for better visitor experience or site statistics.
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie.
The browser may accept the cookie. If it does, it is stored as a plain text record on
the visitor's hard drive. Now, when the visitor arrives at another page on your site,
the browser sends the same cookie to the server for retrieval. Once retrieved, your
server knows/remembers what was stored earlier. Cookies are a plain text data
record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that set the cookie. This may be blank
if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key and value pairs.
Cookies were originally designed for CGI programming and cookies' data is
automatically transmitted between the web browser and web server, so CGI scripts
on the server can read and write cookie values that are stored on the client.
VBScript can also manipulate cookies using the cookie property of
the Document object. VBScript can read, create, modify and delete the cookie or
cookies that apply to the current web page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to
the document.cookie object, which looks like this −
Syntax
document.cookie = "key1 = value1;key2 = value2;expires = date"
Here expires attribute is optional. If you provide this attribute with a valid
date or time, then cookie will expire at the given date or time and after that cookies'
value will not be accessible.
Example
Following is the example to set a customer name in input cookie.
<html>
<head>
<script type = "text/vbscript">
Function WriteCookie
If document.myform.customer.value = "" Then
msgbox "Enter some value!"
Else
cookievalue = (document.myform.customer.value)
document.cookie = "name = " + cookievalue
msgbox "Setting Cookies : " & "name = " & cookievalue
End If
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
It will produce the following result. Now enter something in the textbox and press
the button "Set Cookie" to set the cookies.
Top of Form

Enter name:
Bottom of Form

Now, your system has a cookie called name. You can set multiple cookies using
multiple key = value pairs separated by comma. You will learn how to read this
cookie in next section.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of
the document.cookie object is the cookie. So, you can use this string whenever you
want to access the cookie. The document.cookie string will keep a list of name =
value pairs separated by semicolons where name is the name of a cookie and value
is its string value. You can use strings' split() function to break the string into key
and values as follows −
Example
Following is the example to get the cookies set in the previous section −
<html>
<head>
<script type = "text/vbscript">
Function ReadCookie
allcookies = document.cookie
msgbox "All Cookies : " + allcookies
cookiearray = split(allcookies,";")

For i = 0 to ubound(cookiearray)
Name = Split(cookiearray(i),"=")
Msgbox "Key is : " + Name(0) + " and Value is : " + Name(1)
Next
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>
Note − Here, UBound is a method of Array class, which returns the length of
an array. We will discuss Arrays in a separate chapter; until that time, please try to
digest it.
It will produce the following result. Now, press the button "Get Cookie" to
see the cookies, which you have set in previous section.
Top of Form

Bottom of Form

Note − There may be some other cookies already set on your machine. So, above
code will show you all the cookies set at your machine.
Setting the Cookies Expiration Date
You can extend the life of a cookie beyond the current browser session by setting
an expiration date and saving the expiration date within the cookie. This can be
done by setting the expires attribute to a date and time.
Example
The following example illustrates how to set cookie expiration date after 1 Month

<html>
<head>
<script type = "text/vbscript">
Function WriteCookie()
x = now()
y = dateadd("m",1,now()) ' Making it to expire next
cookievalue = document.myform.customer.value
document.cookie = "name = " & cookievalue
document.cookie = "expires = " & y
msgbox("Setting Cookies : " & "name=" & cookievalue )
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>

Deleting a Cookie
Sometimes, you will want to delete a cookie so that subsequent attempts to
read the cookie return nothing. To do this, you just need to set the expiration date
to a time in the past.
Example
The following example illustrates how to delete a cookie by setting its expiration
date 1 Month in the past −
<html>
<head>
<script type = "text/vbscript">
Function WriteCookie()
x = now()
x = now()
a = Month(x)-1
b = day(x)
c = year(x)
d = DateSerial(c,a,b)
e = hour(x)
msgbox e
f = minute(x)
msgbox f
d = cdate(d & " " & e & ":" & f)
msgbox d
cookievalue = document.myform.customer.value
document.cookie = "name = " & cookievalue
document.cookie = "expires = " & d
msgbox("Setting Cookies : " & "name=" & cookievalue )
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
UNIT - IV
DHTML Introduction
DHTML, or Dynamic HTML, is a technology that differs from traditional
HTML. DHTML combines HTML, CSS, JavaScript, and the Document Object Model
(DOM) to create dynamic content. It uses the Dynamic Object Model to modify
settings, properties, and methods. Scripting is also an essential component of
DHTML, which was part of earlier computing trends. It is supported by some
versions of Netscape Navigator and Internet Explorer 4.0 and higher.
HTML: HTML stands for Hypertext Markup Language and it is a client-side markup
language. It is used to build the block of web pages.
Javascript: It is a Client-side Scripting language. Javascript is supported by most of
browsers, and also has cookie collection to determine the user’s needs.
CSS: The abbreviation of CSS is Cascading Style Sheet. It helps in the styling of the
web pages and helps in designing of the pages. The CSS rules for DHTML will be
modified at different levels using JS with event handlers which adds a significant
amount of dynamism with very little code.
DOM: It is known as a Document Object Model which acts as the weakest link in it.
The only defect in it is that most of the browsers does not support DOM. It is a way
to manipulate the static content.
DHTML is not a technology; rather, it is the combination of three different
technologies, client-side scripting (JavaScript or VBScript), cascading style sheets
and document object model.

Note: Many times DHTML is confused with being a language like HTML but it is not.
It must be kept in mind that it is an interface or browsers enhancement feature
which makes it possible to access the object model through Javascript language and
hence make the webpage more interactive.
Key Features:
Tags and their properties can be changed using DHTML.
It is used for real-time positioning.
Dynamic fonts can be generated using DHTML.
It is also used for data binding.
It makes a webpage dynamic and be used to create animations, games,
applications along with providing new ways of navigating through websites.
The functionality of a webpage is enhanced due to the usage of low-
bandwidth effect by DHTML.
DHTML also facilitates the use of methods, events, properties, and codes.
Why Use DHTML?
DHTML makes a webpage dynamic but Javascript also does, the question
arises that what different does DHTML do? So the answer is that DHTML has the
ability to change a webpages look, content and style once the document has loaded
on our demand without changing or deleting everything already existing on the
browser’s webpage. DHTML can change the content of a webpage on demand
without the browser having to erase everything else, i.e. being able to alter changes
on a webpage even after the document has completely loaded.
Advantages:
Size of the files are compact in compared to other interactional media like
Flash or Shockwave, and it downloads faster.
It is supported by big browser manufacturers like Microsoft and Netscape.
Highly flexible and easy to make changes.
Viewer requires no extra plug-ins for browsing through the webpage that
uses DHTML, they do not need any extra requirements or special software to view
it.
User time is saved by sending less number of requests to the server. As it is
possible to modify and replace elements even after a page is loaded, it is not
required to create separate pages for changing styles which in turn saves time in
building pages and also reduces the number of requests that are sent to the server.
It has more advanced functionality than a static HTML. it is capable of
holding more content on the web page at the same time.
Disadvantages:
It is not supported by all the browsers. It is supported only by recent
browsers such as Netscape 6, IE 5.5, and Opera 5 like browsers.
Learning of DHTML requires a lot of pre-requisites languages such as HTML,
CSS, JS, etc should be known to the designer before starting with DHTML which is a
long and time-consuming in itself.
Implementation of different browsers are different. So if it worked in one
browser, it might not necessarily work the same way in another browser.
Even after being great with functionality, DHTML requires a few tools and
utilities that are some expensive. For example, the DHTML text editor,
Dreamweaver. Along with it the improvement cost of transferring from HTML to
DHTML makes cost rise much higher.
Difference between HTML and DHTML:
HTML is a markup language while DHTML is a collection of technologies.
HTML is used to create static webpages while DHTML is capable of creating
dynamic webpages.
DHTML is used to create animations and dynamic menus but HTML not used.
HTML sites are slow upon client-side technologies whereas DHTML sites are
comparatively faster.
Web pages created using HTML are rather simple and have no styling as it uses only
one language whereas DHTML uses HTML, CSS, and Javascript which results in a
much better and way more presentable webpage.
HTML cannot be used as server side code but DHTML used as server side code.
DHTML needs database connectivity but not in case of HTML.
Files in HTML are stored using .htm or .html extension while DHTML uses .dhtm
extension.
HTML requires no processing from the browser but DHTML does.

What is CSS?
CSS, or Cascading Style Sheets, is a language used to style and enhance websites.
It controls how HTML elements—such as text, images, and buttons—are displayed
on a webpage. With CSS, you can adjust font sizes and colors, add backgrounds,
and manage the layout, transforming a basic webpage into a visually appealing
and user-friendly experience. CSS also simplifies layout management across
multiple web pages by using external stylesheets stored in CSS files.
Different Ways to Use CSS
CSS has three ways to style the HTML:
Inline: Add styles directly to HTML elements using the style attribute (limited
use).
Internal: Place styles within a <style> tag inside the HTML file, usually within
the <head> section
External: Create a separate CSS file with a .css extension and link it to your HTML
file using the <link> tag.
Types of CSS
CSS (Cascading Style Sheet) describes the HTML elements which are
displayed on screen, paper, or in other media. It saves a lot of time. It controls the
layout of multiple web pages at one time. It sets the font-size, font-family, color,
background color on the page.
It allows us to add effects or animations to the website. We use CSS to
display animations like buttons, effects, loaders or spinners, and also animated
backgrounds.
Without using CSS, the website will not look attractive. There are 3 types
of CSS which are below:
Inline CSS
Internal/ Embedded CSS
External CSS

1. Internal CSS
The Internal CSS has <style> tag in the <head> section of
the HTML document. This CSS style is an effective way to style single pages. Using
the CSS style for multiple web pages is time-consuming because we require placing
the style on each web page.
We can use the internal CSS by using the following steps:
1. Firstly, open the HTML page and locate the <head>
2. Put the following code after the <head>
<style type="text/css">
3. Add the rules of CSS in the new line.
Example:
body {
background-color: black;
}
h1 {
color: white;
padding: 50px;
}
4. Close the style tag.
</style>
After adding the internal CSS, the complete HTML file looks like the following:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: black;
}
h1 {
color: red;
padding: 50px;
}
</style>
</head>
<body>
<h2>CSS types</h2>
<p>Cascading Style sheet types: inline, external and internal</p>
</body>
</html>
We can also use the selectors (class and ID) in the style sheet.
Example:
.class {
property1 : value1;
property2 : value2;
property3 : value3;
}

#id {
property1 : value1;
property2 : value2;
property3 : value3;
}
Pros of Internal CSS
Internal CSS cannot upload multiple files when we add the code with the HTML
page.
Cons of Internal CSS:
Adding code in the HTML document will reduce the page size and loading time of
the webpage.
2. External CSS
In external CSS, we link the web pages to the external .css file. It is created
by text editor. The CSS is more efficient method for styling a website. By editing
the .css file, we can change the whole site at once.
To use the external CSS, follow the steps, given below:
1. Create a new .css file with text editor, and add Cascading Style Sheet rules too.
For example:
.xleftcol {
float: right;
width: 35%;
background:#608800;
}
.xmiddlecol {
float: right;
width: 35%;
background:#eff3df;
}
2. Add a reference to the external .cssfile right after <title> tag in
the <head> section of HTML sheet:
<link rel="stylesheet" type="text/css" href="style.css" />
Pros of External CSS:
Our files have a cleaner structure and smaller in size.
We use the same .css file for multiple web pages in external CSS.
Cons of External CSS:
The pages cannot be delivered correctly before the external CSS is loaded.
In External CSS, uploading many CSS files can increase the download time of a
website.
3. Inline CSS
Inline CSS is used to style a specific HTML element. Add a style attribute to
each HTML tag without using the selectors. Managing a website may difficult if we
use only inline CSS. However, Inline CSS in HTML is useful in some situations. We
have not access the CSS files or to apply styles to element.
In the following example, we have used the inline CSS in <p> and <h1> tag.
<!DOCTYPE html>
<html>
<body style="background-color:white;">
<h1 style="color:Red;padding:20px;">CSS Tutorials</h1>
<p style="color:blue;">It will be useful here.</p>
</body>
</html>
Pros of inline CSS:
We can create CSS rules on the HTML page.
We cannot create and upload a separate document in inline CSS.
Cons of inline CSS:
Inline CSS, adding CSS rules to HTML elements is time-
consuming and messes up the HTML structure.
It styles multiple elements at the same time which can affect the page size
and download time of the page.
HTML DOM (Document Object Model) is a hierarchical representation of
HTML documents. It defines the structure and properties of elements on a
webpage, enabling JavaScript to dynamically access, manipulate, and update
content, enhancing interactivity and functionality.
Note: It is called a Logical structure because DOM doesn’t specify any
relationship between objects.
What is DOM?
DOM, or Document Object Model, is a programming interface that
represents structured documents like HTML and XML as a tree of objects. It
defines how to access, manipulate, and modify document elements using
scripting languages like JavaScript.
So basically Document Object Model is an API that represents and interacts
with HTML or XML documents.
The DOM is a W3C (World Wide Web Consortium) standard and it defines
a standard for accessing documents.
The W3C Dom standard is divided into three different parts:
Core DOM – standard model for all document types
XML DOM – standard model for XML documents
HTML DOM – standard model for HTML documents
HTML DOM
HTML DOM is a standard object model and programming interface
for HTML documents. HTML DOM is a way to represent the webpage in
a structured hierarchical way so that it will become easier for programmers and
users to glide through the document.
With HTML DOM, we can easily access and manipulate tags, IDs, classes,
attributes, or elements of HTML using commands or methods provided by the
document object.
Using DOM JavaScript we get access to HTML as well as CSS of the web page
and can also modify the behavior of the HTML elements.
Why is DOM Required?
HTML is used to structure the web pages and Javascript is used to
add behavior to our web pages. When an HTML file is loaded into the browser, the
JavaScript can not understand the HTML document directly. So it interprets and
interacts with the Document Object Model (DOM), which is created by the
browser based on the HTML document.
DOM is basically the representation of the same HTML document but in a
tree-like structure composed of objects. JavaScript can not understand the
tags(<h1>H</h1>) in HTML document but can understand object h1 in DOM.
JavaScript interprets DOM easily, using it as a bridge to access and
manipulate the elements. DOM Javascript allow access to each of the objects (h1,
p, etc) by using different functions.
The Document Object Model (DOM) is essential in web development for several
reasons:
Dynamic Web Pages: It allows you to create dynamic web pages. It enables
the JavaScript to access and manipulate page content, structure, and style
dynamically which gives interactive and responsive web experiences, such as
updating content without reloading the entire page or responding to user actions
instantly.
Interactivity: With the DOM, you can respond to user actions (like clicks, inputs,
or scrolls) and modify the web page accordingly.
Content Updates: When you want to update the content without refreshing the
entire page, the DOM enables targeted changes making the web applications more
efficient and user-friendly.
Cross-Browser Compatibility: Different browsers may render HTML and CSS in
different ways. The DOM provides a standardized way to interact with page
elements.
Single-Page Applications (SPAs): Applications built with frameworks such as
React or Angular, heavily rely on the DOM for efficient rendering and updating of
content within a single HTML page without reloading the full page.
Structure of DOM
DOM can be thought of as a Tree or Forest (more than one tree). The
term structure model is sometimes used to describe the tree-like representation
of a document.
Each branch of the tree ends in a node, and each node contains
objects Event listeners can be added to nodes and triggered on an occurrence of
a given event. One important property of DOM structure models is structural
isomorphism: if any two DOM implementations are used to create a
representation of the same document, they will create the same structure model,
with precisely the same objects and relationships.
Why DOM is called an Object Model?
Documents are modeled using objects, and the model includes not only the
structure of a document but also the behavior of a document and the objects of
which it is composed like tag elements with attributes in HTML.
Properties of DOM
Let’s see the properties of the document object that can be accessed and modified
by the document object.
Representation of the DOM
Window Object: Window Object is object of the browser which is always at top of
the hierarchy. It is like an API that is used to set and access all the properties and
methods of the browser. It is automatically created by the browser.
Document object: When an HTML document is loaded into a window, it
becomes a document object. The ‘document’ object has various properties that
refer to other objects which allow access to and modification of the content of the
web page. If there is a need to access any element in an HTML page, we always
start with accessing the ‘document’ object. Document object is property of
window object.
Form Object: It is represented by form tags.
Link Object: It is represented by link tags.
Anchor Object: It is represented by a href tags.
Form Control Elements: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.
Methods of Document Object
DOM provides various methods that allows users to interact with and manipulate
the document. Some commonly used DOM methods are:

Method Description

write(“string”) Writes the given string on the document.

getElementById() Returns the element having the given id value.

Returns all the elements having the given name


getElementsByName()
value.

Returns all the elements having the given tag


getElementsByTagName()
name.
Method Description

Returns all the elements having the given class


getElementsByClassName()
name.

Example: In this example, We use HTML element id to find the DOM HTML
element.
HTML
<!DOCTYPE html>
<html>
<body>
<h2>GeeksforGeeks</h2>
<!-- Finding the HTML Elements by their Id in DOM -->
<p id="intro">
A Computer Science portal for geeks.
</p>
<p>
This example illustrates the <b>getElementById</b> method.
</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"GeeksforGeeks introduction is: " + element.innerHTML;
</script>
</body>
</html>
Output:
Example : This example describes the representation of the HTML elements in the
tree structure.
html
<table>
<ROWS>
<tr>
<td>Car</td>
<td>Scooter</td>
</tr>
<tr>
<td>MotorBike</td>
<td>Bus</td>
</tr>
</ROWS>
</table>

HTML elements in tree-like structure


What DOM is not?
The Document Object Model is not a binary description where it does not
define any binary source code in its interfaces.
The Document Object Model is not used to describe objects in XML or
HTML whereas the DOM describes XML and HTML documents as objects.
The Document Object Model is not represented by a set of data structures;
it is an interface that specifies object representation.
The Document Object Model does not show the criticality of objects in
documents i.e it doesn’t have information about which object in the document is
appropriate to the context and which is not.
Levels of DOM
DOM consisted of multiple levels, each representing different aspect of the
document.
Level 0: Provides a low-level set of interfaces.
Level 1: DOM level 1 can be described in two parts: CORE and HTML.

CORE provides low-level interfaces that can be used to represent any


structured document.
HTML provides high-level interfaces that can be used to represent HTML
documents.
Level 2: consists of six specifications: CORE2, VIEWS, EVENTS, STYLE, TRAVERSAL,
and RANGE.

CORE2: extends the functionality of CORE specified by DOM level 1.


VIEWS: views allows programs to dynamically access and manipulate the content
of the document.
EVENTS: Events are scripts that are either executed by the browser when the user
reacts to the web page.
STYLE: allows programs to dynamically access and manipulate the content of
style sheets.
TRAVERSAL: This allows programs to dynamically traverse the document.
RANGE: This allows programs to dynamically identify a range of content in the
document.
Level 3: consists of five different specifications: CORE3, LOAD and
SAVE, VALIDATION, EVENTS, and XPATH.

CORE3: extends the functionality of CORE specified by DOM level 2.


LOAD and SAVE: This allows the program to dynamically load the content of the
XML document into the DOM document and save the DOM Document into an XML
document by serialization.
VALIDATION: This allows the program to dynamically update the content and
structure of the document while ensuring the document remains valid.
EVENTS: extends the functionality of Events specified by DOM Level 2.
XPATH: XPATH is a path language that can be used to access the DOM tree.
Example: This example illustrates the dom-manipulation
using getElementById() Method.
HTML
<!DOCTYPE html>
<html>
<head>
<title>DOM manipulation</title>
</head>
<body>
<label>Enter Value 1: </label>
<input type="text" id="val1" />
<br />
<br />
<label>Enter Value 2: </label>
<input type=".text" id="val2" />
<br />
<button onclick="getAdd()">Click To Add</button>
<p id="result"></p>
<script type="text/javascript">
function getAdd() {

// Fetch the value of input with id val1


const num1 = Number(document.getElementById("val1").value);

// Fetch the value of input with id val2


const num2 = Number(document.getElementById("val2").value);
const add = num1 + num2;
console.log(add);

// Displays the result in paragraph using dom


document.getElementById("result").innerHTML = "Addition : " + add;

// Changes the color of paragraph tag with red


document.getElementById("result").style.color = "red";
}
</script>
</body>
</html>
Output:

Manipulating the Document objects using getElementById() Method


Conclusion
HTML DOM is a programming interface enabling modification of web documents
via functions. Focusing on HTML DOM, it empowers JavaScript to manipulate
HTML tags, attributes, and elements. This guide elaborates on DOM properties,
structure, methods, and benefits, fostering comprehensive understanding for
web development.

DHTML DOM
DHTML DOM stands for Dynamic HTML Document Object Model.
It is a w3c standard, which is a standard interface of programming for HTML.
It is mainly used for defining the objects and properties of all elements in HTML. It
also defines the methods for accessing the HTML elements.
Example: The following program helps in understanding the concept of DHTML
DOM. This example changes the color of text and displays the text in red colour
automatically.
<html>
<head>
<title>
Example of DHTML DOM
</title>
</head>
<body>
<font color = "blue">
<p id="demo"> This text changes color when the page loaded. </p>
</font>
<script type="text/javascript">
document.getElementById('demo').style.color = "red";
</script>
</body>
</html>
Output:

DHTML Events
An event is defined as changing the occurrence of an object.
It is compulsory to add the events in the DHTML page. Without events, there will be
no dynamic content on the HTML page. The event is a term in the HTML, which
triggers the actions in the web browsers.
Suppose, any user clicks an HTML element, then the JavaScript code associated
with that element is executed. Actually, the event handlers catch the events
performed by the user and then execute the code.
Example of events:
Click a button.
Submitting a form.
An image loading or a web page loading, etc.
Following table describes the Event Handlers used in the DHTML:

S.No. Event When it occurs

1. onabort It occurs when the user aborts the page or media file loading.

2. onblur It occurs when the user leaves an HTML object.

3. onchange It occurs when the user changes or updates the value of an


object.

4. onclick It occurs or triggers when any user clicks on an HTML


element.
5. ondblclick It occurs when the user clicks on an HTML element two times
together.

6. onfocus It occurs when the user focuses on an HTML element. This


event handler works opposite to onblur.

7. onkeydown It triggers when a user is pressing a key on a keyboard


device. This event handler works for all the keys.

8. onkeypress It triggers when the users press a key on a keyboard. This


event handler is not triggered for all the keys.

9. onkeyup It occurs when a user released a key from a keyboard after


pressing on an object or element.

10. onload It occurs when an object is completely loaded.

11. onmousedown It occurs when a user presses the button of a mouse over an
HTML element.

12. onmousemove It occurs when a user moves the cursor on an HTML object.

13. onmouseover It occurs when a user moves the cursor over an HTML object.

14. onmouseout It occurs or triggers when the mouse pointer is moved out of
an HTML element.

15. onmouseup It occurs or triggers when the mouse button is released over
an HTML element.

16. onreset It is used by the user to reset the form.

17. onselect It occurs after selecting the content or text on a web page.

18. onsubmit It is triggered when the user clicks a button after the
submission of a form.

19. onunload It is triggered when the user closes a web page.

Following are the different examples using the different event handlers,
which helps us to understand the concept of DHTML events:
Example 1: This example uses the onclick event handler, which is used to
change the text after clicking.
<html>
<head>
<title>
Example of onclick event
</title>
<script type="text/javascript">
function ChangeText(ctext)
{
ctext.innerHTML=" Hi JavaTpoint! ";
}
</script>
</head>
<body>
<font color="red"> Click on the Given text for changing it: <br>
</font>
<font color="blue">
<h1 onclick="ChangeText(this)"> Hello World! </h1>
</font>
</body>
</html>
Output:

Example 2: This example uses the onsubmit event handler, which gives an
alert after clicking on a submit button.
<html>
<head>
<title>
Example of onsubmit event
</title>
</head>
<body>
<form onsubmit="Submit_Form()">
<label> Enter your name: </label>
<input type="text">
<label> Enter your Roll no: </label>
<input type="Number">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
function Submit_Form()
{
alert(" Your form is submitted");
}
</script>
</body>
</html>
Output:
UNIT - V:
Extensible Mark-Up Language (XML): Introduction
What is xml
Xml (eXtensible Markup Language) is a mark up language.
XML is designed to store and transport data.
Xml was released in late 90’s. it was created to provide an easy to use and store self
describing data.
XML became a W3C Recommendation on February 10, 1998.
XML is not a replacement for HTML.
XML is designed to be self-descriptive.
XML is designed to carry data, not to display data.
XML tags are not predefined. You must define your own tags.
XML is platform independent and language independent.
Why xml
Platform Independent and Language Independent: The main benefit of xml
is that you can use it to take data from a program like Microsoft SQL, convert it into
XML then share that XML with other programs and platforms. You can
communicate between two platforms which are generally very difficult.
The main thing which makes XML truly powerful is its international acceptance.
Many corporation use XML interfaces for databases, programming, office
application mobile phones and more. It is due to its platform independent feature.
What is the difference between XML and HTML?

XML HTML

XML stands for Extensible Markup HTML stands for a hypertext markup
Language. language.

It is a type of framework used to specify It is a predefined markup language.


that it is a markup language.

It is a case-sensitive language. It is case-insensitive language.

It provides the structural details. It needs to provide the structural details.

The main purpose of XML is used to The main purpose of HTML is used to
transfer the data. create and design the webpage.
It does not allow any error in the coding. If there is a small error in the code, then
it is ignored by the HTML.

Whitespace is allowed in the code of Whitespace is not allowed in the code of


XML. HTML.

In XML, we have to perform the nesting The nesting of code does not affect the
operation appropriately. HTML code.

XML is driven by content. The format drives HTML.

In XML, the closing tag is mandatory. But in HTML, some tags do not have the
closing tag.

XML requires the code around XML Here no quote requires the value of the
attribute values. attribute.

The convention should express all the The HTML natively offers Object
objects in XML. Most of the objects use support.
elements and attributes.

In XML, we need to use xsi:nil on In HTML, the elements are recognized


elements in an XML instance document. with the help of a null value.
We also need to import all the
corresponding namespaces.

XML supports the namespace. With the The concept of namespace does not
help of a namespace, we can remove the supported by HTML. In HTML, we can
collision risk created when we combine avoid the naming collision by
it with another document. implementing prefixes in the object or
performing nesting operations.

In XML, there is a requirement for the In HTML, we can provide direct mapping
connection between the MAP for the application data.
application type to the element and
attribute of the XML.

In XML, we use the document, which is In HTML, we only use formatted text.
very lengthy in size.

In XML, we use the implementation of In HTML, the parsing of javascript there


the XML DOM for parsing the javascript. is no code required for parsing the text.
Learning technology like XPath, XML It is a simple technology that is very
Schema, DOM, etc, is much more popular among the developer.
difficult.

In XML, all the tags are enclosed by the In HTML, all the tags are enclosed by the
closing square bracket. angle bracket.

There is no particular structure in the There is a particular format for writing


XML. HTML code containing tags and
attributes.

XML is neither a programming language With the help of HTML, we can maintain
nor a presentation language. the data presentation on the webpage.

It is a dynamic language. It is a static language.

In XML, data interchange is possible. In HTML, data interchange is not


possible.

XML supports some data types. The HTML supports no concept of datatype.
supported data types are Boolean,
integer, duration, date, etc.

XML - Syntax
we will discuss the simple syntax rules to write an XML document. Following is a
complete XML document −
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
You can notice there are two kinds of information in the above example −
Markup, like <contact-info>
The text, or the character data, Tutorials Point and (040) 123-4567.
The following diagram depicts the syntax rules to write different types of markup
and text in an XML document.
Let us see each component of the above diagram in detail.
XML Declaration
The XML document can optionally have an XML declaration. It is written as follows

<?xml version = "1.0" encoding = "UTF-8"?>
Where version is the XML version and encoding specifies the character encoding
used in the document.
Syntax Rules for XML Declaration
The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is
written in lower-case.
If document contains XML declaration, then it strictly needs to be the first
statement of the XML document.
The XML declaration strictly needs be the first statement in the XML document.
An HTTP protocol can override the value of encoding that you put in the XML
declaration.

XML Attributes
XML elements can have attributes. By the use of attributes we can add the
information about the element.
XML attributes enhance the properties of the elements.
Note: XML attributes must always be quoted. We can use single or double quote.
Let us take an example of a book publisher. Here, book is the element and publisher
is the attribute.
<book publisher="Tata McGraw Hill"></book>
Or
<book publisher='Tata McGraw Hill'></book>
Metadata should be stored as attribute and data should be stored as element.
<book>
<book category="computer">
<author> A & B </author>
</book>
Data can be stored in attributes or in child elements. But there are some limitations
in using attributes, over child elements.

Why should we avoid XML attributes


Attributes cannot contain multiple values but child elements can have multiple
values.
Attributes cannot contain tree structure but child element can.
Attributes are not easily expandable. If you want to change in attribute's vales in
future, it may be complicated.
Attributes cannot describe structure but child elements can.
Attributes are more difficult to be manipulated by program code.
Attributes values are not easy to test against a DTD, which is used to define the legal
elements of an XML document.

Difference between attribute and sub-element


In the context of documents, attributes are part of markup, while sub elements are
part of the basic document contents.
In the context of data representation, the difference is unclear and may be
confusing.
Same information can be represented in two ways:
1st way:
<book publisher="Tata McGraw Hill"> </book>
2nd way:
<book>
<publisher> Tata McGraw Hill </publisher>
</book>
In the first example publisher is used as an attribute and in the second example
publisher is an element.
Both examples provide the same information but it is good practice to avoid
attribute in XML and use elements instead of attributes.
XML Validation:
Validation is a process by which an XML document is validated. An XML
document is said to be valid if its contents match with the elements, attributes and
associated document type declaration(DTD), and if the document complies with
the constraints expressed in it. Validation is dealt in two ways by the XML parser.
They are −
Well-formed XML document
Valid XML document
Well-formed XML Document
An XML document is said to be well-formed if it adheres to the following rules les
for well formed XML
It must begin with the XML declaration.
It must have one unique root element.
All start tags of XML documents must match end tags.
XML tags are case sensitive.
All elements must be closed.
All elements must be properly nested.
All attributes values must be quoted.
XML entities must be used for special characters.
Valid XML document
It must be well formed (satisfy all the basic syntax condition)
It should be behave according to predefined DTD or XML schema.

XML DTD

What is DTD
DTD stands for Document Type Definition. It defines the legal building
blocks of an XML document. It is used to define document structure with a list of
legal elements and attributes.
Purpose of DTD
Its main purpose is to define the structure of an XML document. It contains
a list of legal elements and define the structure with the help of them.

Checking Validation
Before proceeding with XML DTD, you must check the validation. An XML
document is called "well-formed" if it contains the correct syntax.
A well-formed and valid XML document is one which have been validated
against DTD.
Visit http://www.xmlvalidation.com to validate the XML file.

Valid and well-formed XML document with DTD


Let's take an example of well-formed and valid XML document. It follows all the
rules of DTD.
employee.xml
<?xml version="1.0"?>
<!DOCTYPE employee SYSTEM "employee.dtd">
<employee>
<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>vimal@javatpoint.com</email>
</employee>
In the above example, the DOCTYPE declaration refers to an external DTD
file. The content of the file is shown in below paragraph.
employee.dtd
<!ELEMENT employee (firstname,lastname,email)>
<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT email (#PCDATA)>

Description of DTD
<!DOCTYPE employee : It defines that the root element of the document is
employee.
<!ELEMENT employee: It defines that the employee element contains 3 elements
"firstname, lastname and email".
<!ELEMENT firstname: It defines that the firstname element is #PCDATA typed.
(parse-able data type).
<!ELEMENT lastname: It defines that the lastname element is #PCDATA typed.
(parse-able data type).
<!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able
data type).
XML DTD with entity declaration
A doctype declaration can also define special strings that can be used in the XML
file.
An entity has three parts:
An ampersand (&)
An entity name
A semicolon (;)
Syntax to declare entity:
<!ENTITY entity-name "entity-value">
Let's see a code to define the ENTITY in doctype declaration.
author.xml
<?xml version="1.0" standalone="yes" ?>
<!DOCTYPE author [
<!ELEMENT author (#PCDATA)>
<!ENTITY sj "Sonoo Jaiswal">
]>
<author>&sj;</author>
In the above example, sj is an entity that is used inside the author element. In such
case, it will print the value of sj entity that is "Sonoo Jaiswal".
DTD - XML Building Blocks

The main building blocks of both XML and HTML documents are elements.

The Building Blocks of XML Documents


Seen from a DTD point of view, all XML documents are made up by the following
building blocks:
Elements
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
could be "note" and "message". Elements can contain text, other elements, or be
empty. Examples of empty HTML elements are "hr", "br" and "img".
Examples:
<body>some text</body>

<message>some text</message>

Attributes
Attributes provide extra information about elements.
Attributes are always placed inside the opening tag of an element. Attributes
always come in name/value pairs. The following "img" element has 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 by a "
/".

Entities
Some characters have a special meaning in XML, like the less than sign (<) that
defines the start of an XML tag.
Most of you know the HTML entity: "&nbsp;". This "no-breaking-space" entity is
used in HTML to insert an extra space in a document. Entities are expanded when
a document is parsed by an XML parser.
The following entities are predefined in XML:

Entity References Character

&lt; <

&gt; >

&amp; &

&quot; "

&apos; '
PCDATA
PCDATA means parsed character data.
Think of character data as the text found between the start tag and the end tag of
an XML element.
PCDATA is text that WILL be parsed by a parser. The text will be examined by the
parser for entities and markup.
Tags inside the text will be treated as markup and entities will be expanded.
However, parsed character data should not contain any &, <, or > characters; these
need to be represented by the &amp; &lt; and &gt; entities, respectively.

CDATA
CDATA means character data.
CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be
treated as markup and entities will not be expanded.
DTD - Elements

In a DTD, elements are declared with an ELEMENT declaration.

Declaring Elements
In a DTD, XML elements are declared with the following syntax:
<!ELEMENT element-name category>
or
<!ELEMENT element-name (element-content)>

Empty Elements
Empty elements are declared with the category keyword EMPTY:
<!ELEMENT element-name EMPTY>

Example:

<!ELEMENT br EMPTY>

XML example:

<br />

Elements with Parsed Character Data


Elements with only parsed character data are declared with #PCDATA inside
parentheses:
<!ELEMENT element-name (#PCDATA)>

Example:

<!ELEMENT from (#PCDATA)>

ADVERTISEMENT

Elements with any Contents


Elements declared with the category keyword ANY, can contain any combination of
parsable data:
<!ELEMENT element-name ANY>

Example:

<!ELEMENT note ANY>


Attribute gives more information about an element or more precisely it defines a
property of an element. An XML attribute is always in the form of a name-value pair.
An element can have any number of unique attributes.
Attribute declaration is very much similar to element declarations in many ways
except one; instead of declaring allowable content for elements, you declare a list
of allowable attributes for each element. These lists are called ATTLIST
declaration.
Syntax
Basic syntax of DTD attributes declaration is as follows −
<!ATTLIST element-name attribute-name attribute-type attribute-value>
In the above syntax −
The DTD attributes start with <!ATTLIST keyword if the element contains the
attribute.
element-name specifies the name of the element to which the attribute applies.
attribute-name specifies the name of the attribute which is included with the
element-name.
attribute-type defines the type of attributes. We will discuss more on this in the
following sections.
attribute-value takes a fixed value that the attributes must define. We will discuss
more on this in the following sections.
Example
Below is a simple example for attribute declaration in DTD −
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #REQUIRED>
]>

<address>
<name id = "123">Tanmay Patil</name>
</address>
Let us go through the above code −
Begin with the XML declaration with the following statement −
<?xml version = "1.0"?>
Immediately following the XML header is the document type declaration,
commonly referred to as the DOCTYPE as shown below −
The DOCTYPE informs the parser that a DTD is associated with this XML document.
The DOCTYPE declaration has an exclamation mark (!) at the start of the element
name.
<!DOCTYPE address [
Following is the body of DTD. Here we have declared element and attribute −
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
Attribute id for the element name is defined as given below −
Here attribute type is CDATA and its value is #REQUIRED.
<!ATTLIST name id CDATA #REQUIRED>
Rules of Attribute Declaration
All attributes used in an XML document must be declared in the Document Type
Definition (DTD) using an Attribute-List Declaration
Attributes may only appear in start or empty tags.
The keyword ATTLIST must be in upper case
No duplicate attribute names will be allowed within the attribute list for a given
element.
Attribute Types
When declaring attributes, you can specify how the processor should handle the
data that appears in the value. We can categorize attribute types in three main
categories −
String type
Tokenized types
Enumerated types
Following table provides a summary of the different attribute types −

Sr.No. Type & Description

CDATA
1 CDATA is character data (text and not markup). It is a String Attribute
Type.

ID
2 It is a unique identifier of the attribute. It should not appear more
than once. It is a Tokenized Attribute Type.

IDREF
3 It is used to reference an ID of another element. It is used to establish
connections between elements. It is a Tokenized Attribute Type.

IDREFS
4
It is used to reference multiple ID's. It is a Tokenized Attribute Type.

ENTITY
5 It represents an external entity in the document. It is a Tokenized
Attribute Type.

ENTITIES
6 It represents a list of external entities in the document. It is
a Tokenized Attribute Type.

NMTOKEN
7 It is similar to CDATA and the attribute value consists of a valid XML
name. It is a Tokenized Attribute Type.

NMTOKENS
8 It is similar to CDATA and the attribute value consists a list of valid
XML name. It is a Tokenized Attribute Type.

9 NOTATION
An element will be referenced to a notation declared in the DTD
document. It is an Enumerated Attribute Type.

Enumeration
10 It allows defining a specific list of values where one of the values must
match. It is an Enumerated Attribute Type.

Attribute Value Declaration


Within each attribute declaration, you must specify how the value will appear in
the document. You can specify if an attribute −
can have a default value
can have a fixed value
is required
is implied
Default Values
It contains the default value. The values can be enclosed in single quotes(') or
double quotes(").
Syntax
Following is the syntax of value −
<!ATTLIST element-name attribute-name attribute-type "default-value">
where default-value is the attribute value defined.
Example
Following is a simple example of attribute declaration with default value −
<?xml version = "1.0"?>

<!DOCTYPE address [
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA "0">
]>

<address>
<name id = "123">
Tanmay Patil
</name>
</address>
In this example we have name element with attribute id whose default value is 0.
The default value is been enclosed within the double quotes.
FIXED Values
#FIXED keyword followed by the fixed value is used when you want to specify that
the attribute value is constant and cannot be changed. A common use of fixed
attributes is specifying version numbers.
Syntax
Following is the syntax of fixed values −
<!ATTLIST element-name attribute-name attribute-type #FIXED "value" >
where #FIXED is an attribute value defined.
Example
Following is a simple example of attribute declaration with FIXED value −
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address (company)*>
<!ELEMENT company (#PCDATA)>
<!ATTLIST company name NMTOKEN #FIXED "tutorialspoint">
]>
<address>
<company name = "tutorialspoint">we are a free online teaching
faculty</company>
</address>
In this example we have used the keyword #FIXED where it indicates that the value
"tutorialspoint" is the only value for the attribute name of element <company>. If
we try to change the attribute value then it gives an error.
Following is an invalid DTD −
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address (company)*>
<!ELEMENT company (#PCDATA)>
<!ATTLIST company name NMTOKEN #FIXED "tutorialspoint">
]>
<address>
<company name = "abc">we are a free online teaching faculty</company>
</address>
REQUIRED values
Whenever you want specify that an attribute is required, use #REQUIRED keyword.
Syntax
Following is the syntax of #REQUIRED −
<!ATTLIST element-name attribute-name attribute-type #REQUIRED>
where #REQUIRED is an attribute type defined.
Example
Following is a simple example of DTD attribute declaration with #REQUIRED
keyword −
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #REQUIRED>
]>
<address>
<name id = "123">
Tanmay Patil
</name>
</address>
In this example we have used #REQUIRED keyword to specify that the
attribute id must be provided for the element-name name
IMPLIED Values
When declaring attributes you must always specify a value declaration. If the
attribute you are declaring has no default value, has no fixed value, and is not
required, then you must declare that the attribute as implied. Keyword #IMPLIED
is used to specify an attribute as implied.
Syntax
Following is the syntax of #IMPLIED −
<!ATTLIST element-name attribute-name attribute-type #IMPLIED>
where #IMPLIED is an attribute type defined.
Example
Following is a simple example of #IMPLIED
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #IMPLIED>
]>

<address>
<name />
</address>
In this example we have used the keyword #IMPLIED as we do not want to specify
any attributes to be included in element name. It is optional.
DTD - Entities
Entities are used to define shortcuts to special characters within the XML
documents. Entities can be primarily of four types −
Built-in entities
Character entities
General entities
Parameter entities
Entity Declaration Syntax
In general, entities can be declared internally or externally. Let us understand each
of these and their syntax as follows −
Internal Entity
If an entity is declared within a DTD it is called as internal entity.
Syntax
Following is the syntax for internal entity declaration −
<!ENTITY entity_name "entity_value">
In the above syntax −
entity_name is the name of entity followed by its value within the double quotes or
single quote.
entity_value holds the value for the entity name.
The entity value of the Internal Entity is de-referenced by adding prefix & to the
entity name i.e. &entity_name.
Example
Following is a simple example for internal entity declaration −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>

<!DOCTYPE address [
<!ELEMENT address (#PCDATA)>
<!ENTITY name "Tanmay patil">
<!ENTITY company "TutorialsPoint">
<!ENTITY phone_no "(011) 123-4567">
]>

<address>
&name;
&company;
&phone_no;
</address>
In the above example, the respective entity
names name, company and phone_no are replaced by their values in the XML
document. The entity values are de-referenced by adding prefix & to the entity
name.
Save this file as sample.xml and open it in any browser, you will notice that
the entity values for name, company, phone_no are replaced respectively.
External Entity
If an entity is declared outside a DTD it is called as external entity. You can
refer to an external Entity by either using system identifiers or public identifiers.
Syntax
Following is the syntax for External Entity declaration −
<!ENTITY name SYSTEM "URI/URL">
In the above syntax −
name is the name of entity.
SYSTEM is the keyword.
URI/URL is the address of the external source enclosed within the double or single
quotes.
Types
You can refer to an external DTD by either using −
System Identifiers − A system identifier enables you to specify the location of an
external file containing DTD declarations.
As you can see it contains keyword SYSTEM and a URI reference pointing to
the document's location. Syntax is as follows −
<!DOCTYPE name SYSTEM "address.dtd" [...]>
Public Identifiers − Public identifiers provide a mechanism to locate DTD
resources and are written as below −
As you can see, it begins with keyword PUBLIC, followed by a specialized
identifier. Public identifiers are used to identify an entry in a catalog. Public
identifiers can follow any format; however, a commonly used format is
called Formal Public Identifiers, or FPIs.
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
Example
Let us understand the external entity with the following example −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<!DOCTYPE address SYSTEM "address.dtd">

<address>
<name>
Tanmay Patil
</name>
<company>
TutorialsPoint
</company>
<phone>
(011) 123-4567
</phone>
</address>
Below is the content of the DTD file address.dtd −
<!ELEMENT address (name, company, phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Built-in entities
All XML parsers must support built-in entities. In general, you can use these
entity references anywhere. You can also use normal text within the XML
document, such as in element contents and attribute values.
There are five built-in entities that play their role in well-formed XML, they are −
ampersand: &amp;
Single quote: &apos;
Greater than: &gt;
Less than: &lt;
Double quote: &quot;
Example
Following example demonstrates the built-in entity declaration −
<?xml version = "1.0"?>
<note>
<description>I'm a technical writer & programmer</description>
<note>
As you can see here the &amp; character is replaced by & whenever the processor
encounters this.
Character entities
Character Entities are used to name some of the entities which are symbolic
representation of information i.e characters that are difficult or impossible to type
can be substituted by Character Entities.
Example
Following example demonstrates the character entity declaration −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<!DOCTYPE author[
<!ELEMENT author (#PCDATA)>
<!ENTITY writer "Tanmay patil">
<!ENTITY copyright "&#169;">
]>
<author>&writer;&copyright;</author>
You will notice here we have used &#169; as value for copyright character.
Save this file as sample.xml and open it in your browser and you will see that
copyright is replaced by the character ©.
General entities
General entities must be declared within the DTD before they can be used
within an XML document. Instead of representing only a single character, general
entities can represent characters, paragraphs, and even entire documents.
Syntax
To declare a general entity, use a declaration of this general form in your DTD −
<!ENTITY ename "text">
Example
Following example demonstrates the general entity declaration −
<?xml version = "1.0"?>

<!DOCTYPE note [
<!ENTITY source-text "tutorialspoint">
]>
<note>
&source-text;
</note>
Whenever an XML parser encounters a reference to source-text entity, it will
supply the replacement text to the application at the point of the reference.
Parameter entities
The purpose of a parameter entity is to enable you to create reusable
sections of replacement text.
Syntax
Following is the syntax for parameter entity declaration −
<!ENTITY % ename "entity_value">
entity_value is any character that is not an '&', '%' or ' " '.
Example
Following example demonstrates the parameter entity declaration. Suppose you
have element declarations as below −
<!ELEMENT residence (name, street, pincode, city, phone)>
<!ELEMENT apartment (name, street, pincode, city, phone)>
<!ELEMENT office (name, street, pincode, city, phone)>
<!ELEMENT shop (name, street, pincode, city, phone)>
Now suppose you want to add additional eleement country, then then you need to
add it to all four declarations. Hence we can go for a parameter entity reference.
Now using parameter entity reference the above example will be −
<!ENTITY % area "name, street, pincode, city">
<!ENTITY % contact "phone">
Parameter entities are dereferenced in the same way as a general entity reference,
only with a percent sign instead of an ampersand −
<!ELEMENT residence (%area;, %contact;)>
<!ELEMENT apartment (%area;, %contact;)>
<!ELEMENT office (%area;, %contact;)>
<!ELEMENT shop (%area;, %contact;)>
When the parser reads these declarations, it substitutes the entity's replaceme
XSL (Extensible Stylesheet Language)
What is XSL (Extensible Stylesheet Language)?
XSL (Extensible Stylesheet Language) is a family of standards that specifies
how to define Extensible Markup Language (XML) document transformation and
presentation. The standards are published by the World Wide Web Consortium
(W3C), an international community that develops specifications related to web
architecture, design, applications and other web technologies.

You might also like