FSD MODULE-2-JavaScript PDF
FSD MODULE-2-JavaScript PDF
JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used by
several websites for scripting the webpages. It is an interpreted, full-fledged programming
language that enables dynamic interactivity on websites when applied to an HTML
document. It was introduced in the year 1995 for adding programs to the webpages in the
Netscape Navigator browser.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it
is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
8. It provides good control to the users over the web browsers.
Example
<html>
<body>
document.write("Hello World!")
</script>
</body>
</html>
1|Dept. of MCA
MODULE – II NECN
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily interpret
the code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
1. Single-line Comment
2. Multi-line Comment
It is represented by double forward slashes (//). It can be used before and after the
statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For
example:
Example:
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
2|Dept. of MCA
MODULE – II NECN
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables
in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
var x = 10;
var _value="sonoo";
var 123=30;
var *aa=320;
example
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
A JavaScript local variable is declared inside block or function. It is accessible within the
function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
3|Dept. of MCA
MODULE – II NECN
</script>
A JavaScript global variable is accessible from any function. A variable i.e. declared outside
the function or declared with window object is known as global variable. For example:
<script>
var data=200;//gloabal variable
function
a(){ document.writeln(data);
}
function
b(){ document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the
data type. It can hold any type of values such as numbers, strings etc. For example:
There are five types of primitive data types in JavaScript. They are as follows:
4|Dept. of MCA
MODULE – II NECN
JavaScript operators are symbols that are used to perform operations on operands. For
example:
var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
5|Dept. of MCA
MODULE – II NECN
4. Logical Operators
5. Assignment Operators
6. Special Operators
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:
Example
10==20 = false
10==20 = false
6|Dept. of MCA
MODULE – II NECN
The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:
7|Dept. of MCA
MODULE – II NECN
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.
8|Dept. of MCA
MODULE – II NECN
Expressions in JavaScript
An expression is a block of code that evaluates to a value. A statement is any block of code
that is performing some action.
Conceptually speaking, there are two kinds of expressions: those that perform some sort of
assignment and those that evaluate to a value.
On the flip side, the expression 10 + 9 simply evaluates to 19. These expressions make use of
simple operators.
9|Dept. of MCA
MODULE – II NECN
Left-hand side expressions: Left-hand side values which are the destination for the
assignment operator
Primary expressions
this:
this is used to refer to the current object; it usually refers to the method or object that calls
it.
this is used either with the dot operator or the bracket operator.
this['element']
this.element
Grouping operator
a*b-c
a * (b - c)
a * b - c applies the multiplication operator first and then evaluates the result of the
multiplication with - b, while a * (b - c) evaluates the brackets first.
new
new creates an instance of the object specified by the user and has the following prototype.
super
super calls on the current object’s parent and is useful in classes to call the parent object’s
constructor.
Function arguments
The arguments of a function must be an expression, not statements. For example, we can
pass in a variable assignment expression as an argument, but we cannot declare a variable
10 | D e p t . o f M C A
MODULE – II NECN
const function
myFunc(arg){ console.log(arg);
}
myFunc("This is okay");
myFunc(true ? "This is okay" : None);
var x = 10
myFunc(if(x > 10){'This will not work'});
As a rule of thumb, any code snippet that can be passed on to the console.log function and
printed can be used as an argument for a function.
JavaScript If statement
The JavaScript if-else statement is used to execute the code whether condition is true or
false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.
if(expression){
//content to be evaluated
}
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
11 | D e p t . o f M C A
MODULE – II NECN
}
</script>
Output of the above example
value of a is greater than 10
12 | D e p t . o f M C A
MODULE – II NECN
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
a is even number
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
13 | D e p t . o f M C A
MODULE – II NECN
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Output of the above example
a is equal to 20
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is
just like else if statement that we have learned in previous page. But it is convenient
than if..else..if because it can be used with numbers, characters etc.
switch(expression){
case value1:
code to be executed;
break;
14 | D e p t . o f M C A
MODULE – II NECN
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
<script>
var grade='B';
var result;
switch(grade){ c
ase 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Output of the above example
B Grade
15 | D e p t . o f M C A
MODULE – II NECN
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be
used if number of iteration is known. The syntax of for loop is given below.
The JavaScript while loop iterates the elements for the infinite number of times. It should be
used if number of iteration is not known. The syntax of while loop is given below.
16 | D e p t . o f M C A
MODULE – II NECN
while (condition)
{
code to be executed
}
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Output:
11
12
13
14
15
The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.
do{
code to be executed
}while (condition);
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
17 | D e p t . o f M C A
MODULE – II NECN
</script>
Output:
21
22
23
24
25
For-in loop in JavaScript is used to iterate over the properties of an object. It can be a
great debugging tool if we want to show the contents of an object
Syntax:
for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
}
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 template based not class based. Here, we don't create class to get the object.
But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
18 | D e p t . o f M C A
MODULE – II NECN
object={property1:value1,property2:value2........ propertyN:valueN}
<script>
emp={id:102,name:"samuel",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Output of the above example
102 samuel 40000
<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
Here, you need to create function with arguments. Each argument value can be assigned in
the current object by using this keyword.
<script>
function
emp(id,name,salary){ this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.
<script>
function
emp(id,name,salary){ this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function
changeSalary(otherSalary){ this.salary
=otherSalary;
}
}
20 | D e p t . o f M C A
MODULE – II NECN
21 | D e p t . o f M C A
MODULE – II NECN
22 | D e p t . o f M C A
MODULE – II NECN
23 | D e p t . o f M C A
MODULE – II NECN
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
var arrayname=[value1,value2.......valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
<script>
var emp=["Sonoo","Vimal","Ratan"];
for
(i=0;i<emp.length;i++){ document.wri
te(emp[i] + "<br/>");
}
</script>
Sonoo
Vimal
Ratan
<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>
Arun
Varun
John
Here, you need to create instance of array by passing arguments in constructor so that we
don't have to provide value explicitly.
<script>
var emp=new Array("Jai","Vijay","Smith");
for
(i=0;i<emp.length;i++){ document.write(em
p[i] + "<br>");
}
</script>
25 | D e p t . o f M C A
MODULE – II NECN
Jai
Vijay
Smith
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
Let’s see the simple example of function in JavaScript that does not has arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
Output of the above example
We can call function by passing arguments. Let’s see the example of function that has one argument.
26 | D e p t . o f M C A
MODULE – II NECN
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Output of the above example
We can call function that returns a value and use it in our program. Let’s see the example of
function that returns value.
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Output of the above example
hello javatpoint! How r u?
Constructor in JavaScript
A constructor is a function that creates an instance of a class which is typically called an
“object”. In JavaScript, a constructor gets called when you declare an object using
the new keyword.
The purpose of a constructor is to create an object and set values if there are any object
properties present. It’s a neat way to create an object because you do not need to explicitly
state what to return as the constructor function, by default, returns the object that gets
created within it.
Example
Let’s say there is an object, User, which has two properties: firstname and lastname.
27 | D e p t . o f M C A
MODULE – II NECN
To initialize two instances with different names, you will use the same constructor function,
as shown in the figure below:
Function User(first,
this.lastName = last
}
Var user1 = new User("Jon","Snow")
console.log(user1)
console.log(user2)
Output
User { firstName: 'Jon', lastName: 'Snow' } User { firstName: 'Ned', lastName: 'Stark' }
Default constructors
constructor()
Note: Constructors have the same name as that of the object which is being created. As a
convention, the first alphabet is kept capital in the constructor function.
28 | D e p t . o f M C A
MODULE – II NECN
Syntax:
/pattern/modifiers;
Example:
var patt = /Java script/i;
Examples:
Expressions Description
Examples:
Metacharacter Description
29 | D e p t . o f M C A
MODULE – II NECN
Examples:
Quantifier Description
The search() method uses an expression to search for a match, and returns the position of
the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search() With a Regular Expression :
Use a regular expression to do a case-insensitive search for “java script” in a string:
Example:
function myFunction() {
// input string
var str = " JavaScript follows the syntax and structure of the C programming!";
// searching string with modifier i
var n = str.search(/JavaScript /i);
document.write(n + '<br>');
// searching string without modifier i
var n = str.search(/JavaScript /);
document.write(n);
}
myFunction();
Output:
6
-1
30 | D e p t . o f M C A
MODULE – II NECN
// input string
var str = " JavaScript follows the syntax and structure of the C programming!";
document.write(txt);
myFunction();
Output:
JavaScript follows the syntax and structure of the C programming language!
31 | D e p t . o f M C A
MODULE – II NECN
Types of Errors
o throw statements
o try…catch statements
o try…catch…finally statements.
JavaScript try…catch
try{} statement: Here, the code which needs possible error testing is kept within the try
block. In case any error occur, it passes to the catch{} block for taking suitable actions and
handle the error. Otherwise, it executes the code written within.
32 | D e p t . o f M C A
MODULE – II NECN
catch{} statement: This block handles the error of the code by executing the set of
statements written within the block. This block contains either the user-defined exception
handler or the built-in handler. This block executes only when any error-prone code needs
to be handled in the try block. Otherwise, the catch block is skipped.
Syntax:
try{
expression; } //code to be written.
catch(error){
expression; } // code for handling the error.
try…catch example
<html>
<head> Exception Handling</br></head>
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a); // displays elements of a
document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be
invoked
}catch(e){
alert("There is error which shows "+e.message); //Handling error
}
</script>
</body>
</html>
Throw Statement
Throw statements are used for throwing user-defined errors. User can define and throw
their own custom errors. When throw statement is executed, the statements present after
it will not execute. The control will directly pass to the catch block.
Syntax:
throw exception;
try…catch…throw syntax
try{
throw exception; // user can define their own exception
33 | D e p t . o f M C A
MODULE – II NECN
}
catch(error){
expression; } // code for handling exception.
With the help of throw statement, users can create their own errors.
try…catch…finally statements
Finally is an optional block of statements which is executed after the execution of try and
catch statements. Finally block does not hold for the exception to be thrown. Any exception
is thrown or not, finally block code, if present, will definitely execute. It does not care for the
output too.
Syntax:
try{ expressio
n;
}
catch(error){ e
xpression;
}
finally{
expression; } //Executable code
34 | D e p t . o f M C A
MODULE – II NECN
try…catch…finally example
<html>
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
</html>
35 | D e p t . o f M C A
MODULE – II NECN
Built-in Objects
Built-in objects are not related to any Window or DOM object model.
These objects are used for simple data processing in the JavaScript.
1. Math Object
PI Returns Π value.
Math Methods
Methods Description
36 | D e p t . o f M C A
MODULE – II NECN
<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">
2. Date Object
Date object allows you to get and set the year, month, day, hour, minute, second and
millisecond fields.
Syntax:
var variable_name = new Date();
Example:
var current_date = new Date();
Date Methods
Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.
38 | D e p t . o f M C A
MODULE – II NECN
<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html>
3. String Object
Example:
var s = new String(string);
String Properties
39 | D e p t . o f M C A
MODULE – II NECN
Properties Description
constructor It returns the reference to the String function that created the object.
String Methods
Methods Description
charCodeAt() It returns the ASCII code of the character at the specified position.
concat() It combines the text of two strings and returns a new string.
split() It splits a string object into an array of strings by separating the string into the
substrings.
<html>
<body>
40 | D e p t . o f M C A
MODULE – II NECN
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
<center>
</body>
</html>
41 | D e p t . o f M C A
MODULE – II NECN
(or)
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form
validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
In this example, we are going to validate the name and password. The name can’t be empty
and password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next
page until given values are correct.
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null ||
name==""){ alert("Name can't
be blank"); return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
42 | D e p t . o f M C A
MODULE – II NECN
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){ retur
n true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
<script>
function validate(){
var num=document.myform.num.value;
43 | D e p t . o f M C A
MODULE – II NECN
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
There are many criteria that need to be follow to validate the email id such as:
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=x.length){ alert("Please enter a valid e-
mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
44 | D e p t . o f M C A
MODULE – II NECN
</form>
45 | D e p t . o f M C A
MODULE – II NECN
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser.
When JavaScript code is included in HTML, js react over these events and allow the
execution. This process of reacting over the events is called Event Handling. Thus, js handles
the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task
to be performed on the event.
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the
element
mousedown onmousedown When the mouse button is pressed over the element
Keyboard events:
Keydown & Keyup onkeydown & When the user press and then release the
onkeyup key
46 | D e p t . o f M C A
MODULE – II NECN
Form events:
Window/Document events
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
Examples:
Click Event
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaScript on Clickevent");
}
//-->
47 | D e p t . o f M C A
MODULE – II NECN
</script>
<form>
MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is on mouseoverevent");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
48 | D e p t . o f M C A
MODULE – II NECN
}
//-->
</script>
</body>
</html>
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
49 | D e p t . o f M C A
MODULE – II NECN
DHTML JavaScript
DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be
customized or changed according to user inputs i.e. a page that is interactive with the user.
In earlier times, HTML was used to create a static page. It only defined the structure of the
content that was displayed on the page. With the help of CSS, we can beautify the HTML
page by changing various properties like text size, background color etc.
DHTML came into existence. DHTML included JavaScript along with HTML and CSS to make
the page dynamic. This combo made the web pages dynamic and eliminated this problem of
creating static page for each user. To integrate JavaScript into HTML, a Document Object
Model (DOM) is made for the HTML document. In DOM, the document is represented as
nodes and objects which are accessed by different languages like JavaScript to manipulate
the document.
HTML document include JavaScript:: The JavaScript document is included in our html
page using the html tag. <src> tag is used to specify the source of external JavaScript file.
Following are some of the tasks that can be performed with JavaScript:
Performing html tasks
Performing CSS tasks
Handling events
Validating inputs
Example 1: Example to understand how to use JavaScript in DHTML.
<html>
<head>
<title>DOM programming</title>
</head>
<body>
<h1>DHTML With JavaScript</h1>
<p id = "DH">Hello DHTML!</p>
50 | D e p t . o f M C A
MODULE – II NECN
}
}
</script>
</body>
</html>
DHTML CSS
We can easily use the CSS with the DHTML page with the help of JavaScript and HTML DOM.
With the help of this.style.property=new style statement, we can change the style of the
currently used HTML element. Or, we can also update the style of any particular HTML
element by document.getElementById(id).style.property = new_style statement.
Example 1: The following example uses the DHTML CSS for changing the style of current
element:
<html>
<head>
<title>
Changes current HTML element
</title>
</head>
<body>
<center>
<h1 onclick="this.style.color='blue'"> This is a JavaTpoint Site </h1>
<center>
</body>
</html>
52 | D e p t . o f M C A
MODULE – II NECN
Example 2: The following example uses the DHTML CSS for changing the style of the
HTML element:
<html>
<head>
<title>
changes the particular HTML element example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different buttons. </
p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">
function change_Color(newColor) {
var element = document.getElementById('demo').style.color = newColor;
}
</script>
</body>
</html>
53 | D e p t . o f M C A
MODULE – II NECN
When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.
window.document
document
According to W3C - "The W3C Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."
54 | D e p t . o f M C A
MODULE – II NECN
Method Description
writeln("string") writes the given string on the doucment with newline character at
the end.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
55 | D e p t . o f M C A