Module 3
Module 3
Overview of JavaScript
● JavaScript was developed by Netscape, originally named Mocha, then LiveScript, and
finally JavaScript in 1995.
● It became a joint effort with Sun Microsystems.
● The language standard is called ECMAScript (ECMA-262), developed by ECMA.
● Core JS – Basic language features (operators, statements, functions).
● Client-Side JS – Runs in the browser, interacts with users and HTML.
Server-Side JS – Runs on the server, used for backend tasks (less common).
● JavaScript code is called a script.
Client-side JS is embedded in HTML/XHTML pages.
Uses of JavaScript
● JavaScript was introduced to enable programming at both client and server ends of web
applications.
🔹 Client-Side JavaScript
● Runs in the browser, embedded in HTML/XHTML.
● Handles user interactions (buttons, forms, mouse movements).
● Can validate form inputs and give instant feedback without contacting the server.
● Helps reduce server workload by handling simple computations on the client side.
● Supports dialog boxes for input and choices.
● Can dynamically update web content.
● Uses DOM (Document Object Model) to access and modify HTML elements and CSS
styles.
🔹 Server-Side JavaScript
Module-3 Javascript and DOM Manipulation
A variable in JavaScript is a named container for storing data. It allows you to reuse and manipulate
data throughout your [Link] allow you to label data with a descriptive name, so your programs
can be understood more clearly by both humans and computers.
Declaring Variables:
● Gets hoisted (declared at the top of the function regardless of where it's written).
Example:-
function greetUser() {
var name = "MCA";
[Link]("Hello, " + name);
}
greetUser(); // Output: Hello, MCA
[Link](name); // Error: name is not defined (var is function-scoped)
Module-3 Javascript and DOM Manipulation
2. let (Modern, block-scoped)
● Block-scoped (confined to {} blocks like loops or if-statements).
● Also gets hoisted, but not initialized until code execution reaches the statement.
● syntax:- let b = 20;
Example:-
function greetUser() {
Example:-
const pi = 3.14159;
● Case-sensitive
Dynamic Typing
Module-3 Javascript and DOM Manipulation
JavaScript is a dynamically typed language, meaning:
Scope of Variables
1. Global Scope
● Declared outside any function/block.
● Accessible anywhere in the script.
2. Function Scope (with var)
● Declared inside a function.
● Only accessible within that function.
3. Block Scope (with let and const)
● Declared inside {} such as in loops, if-else, etc.
● Only accessible within the block.
Ex:-
let x = 5;
[Link](x); // 5
● What is an Operator?
In JavaScript, an operator is a symbol that performs an operation on one or more operands, such as
variables or values, and returns a result. Let us take a simple expression 4 + 5 is equal to 9. Here 4
and 5 are called operands, and + is called the operator.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Bitwise Operators
Assignment Operators
Module-3 Javascript and DOM Manipulation
[Link] Arithmetic Operators
The JavaScript arithmetic operators are used to perform mathematical calculations such as addition,
multiplication, subtraction, division, etc. on numbers. JavaScript supports the following arithmetic
operators −
The comparison operators are used in logical expressions. A logical expression is evaluated to
either true or false.
The comparison operators are binary operators as they perform operations on two operands. The
operands can be numerical, string, logical, or object values.
There are eight comparison operators in JavaScript to perform different types of comparison. Here,
we have given a table explaining each comparison operator with the example.
== Equal x == y
!= Not Equal x != y
!== Strict inequality (not equal value or not equal type) x !== y
Module-3 Javascript and DOM Manipulation
> Greater than x>y
Although the logical operators are typically used with Boolean values, they can be used with any
type. For each non-boolean value, the operator converts to a boolean. The falsy values are
converted to false and truthy values to true.
The && and || operators return the value of one of the operands based on condition. So if the
operands are non-boolean, they return a non-boolean value. The ! operator always returns a Boolean
value.
The operands may be literals, variables or expressions. These are first evaluated to the boolean
equivalent before performing the logical operation.
In the below table, we have given the logical operators with its description and example. Let's
assume: x = true, y = false.
|| Logical OR (x || y) is true.
x && y
In the above expression if x is a falsy value then it will return the value of x otherwise it will return
the value of y.
Module-3 Javascript and DOM Manipulation
The above rule is followed for all types of operands, whether they are Boolean values, numbers or
strings, etc.
Let's first discuss Boolean operands. In general, for a set of Boolean operands, it will return true if
both operands are true else it returns false.
x || y
In the above expression if x is a truthy value then it will return the value of x otherwise it will return
the value of y.
As || is a logical operator but it can be applied to any type of operand not only boolean.
Let's first discuss Boolean operands. In general, for a set of Boolean operands, it will return false if
both operands are false else it returns true.
!x
If x is truthy, the NOT (!) operator returns false. If the x is false then it returns true.
Same as Logical AND, and OR operators, this logical NOT operator can also be used with
non-boolean operands. But it will always return a Boolean value.
JavaScript bitwise operators work on 32-bits operands. In JavaScript, numbers are stored as 64-bit
floating point numbers. JavaScript converts the numbers to 32-bit signed integers before performing
the operation. After bitwise operation, it converts the result to 64-bits.
There are seven bitwise operators in JavaScript. Following is the list of bitwise operators with
description.
<< Left Shift Shifts the bits left by pushing zeros in from right and
discarding leftmost bits.
>> Right Shift Shift the bits right by pushing copies of the leftmost bit in
from the left and discarding rightmost bits.
>>> Right Shift with Shifts the bits right by pushing zeros in from left and
Zero discarding rightmost bits.
When bitwise AND operator is applied on a pair of bits, it returns 1 if both bits are 1, otherwise
returns 0.
<html>
<body>
<div id="output"></div>
<script>
const a = 5;
const b = 7;
</script>
</body>
</html>
When bitwise OR operator is applied on a pair of bits, it returns 1 if either of bits is 1, otherwise
returns 0.
<html>
<body>
<div id="output"></div>
<script>
const a = 5;
const b = 7;
</script>
</body>
</html>
When bitwise XOR operator is applied on a pair of bits, it returns 1 if both bits are different,
otherwise returns 0.
<html>
<body>
<div id="output"></div>
<script>
const a = 5;
const b = 7;
</script>
Module-3 Javascript and DOM Manipulation
</body>
</html>
<html>
<body>
<div id="output"></div>
<script>
const a = 5;
const b = 7;
[Link]("output").innerHTML =
</script>
</body>
</html>
Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.
<html>
<body>
<div id="output"></div>
Module-3 Javascript and DOM Manipulation
<script>
const a = 5;
[Link]("output").innerHTML =
</script>
</body>
</html>
In short, it removes the N last bits from the number. Here, N is a second operand. Right-shifting the
binary number is equivalent to dividing the decimal number by 2.
<html>
<body>
<div id="output"></div>
<script>
const a = 5;
[Link]("output").innerHTML =
</script>
</body>
</html>
<html>
<body>
<div id="output"></div>
<script>
const a = 5;
</script>
</body>
</html>
An assignment operator first evaluates the expression and then assign the value to the variable (left
operand).
A simple assignment operator is an equal (=) operator. In the JavaScript statement "let x = 10;", the
= operator assigns 10 to the variable x.
We can combine a simple assignment operator with other type of operators such as arithmetic,
logical, etc. to get compound assignment operators. Some arithmetic assignment operators are +=,
-=, *=, /=, etc. The += operator performs addition operation on the operands and assign the result to
the left hand operand.
x += b;
In the above statement, it adds values of b and x and assigns the result to x.
<html>
<body>
<div id="output"></div>
<script>
let x = 5;
x += 7;
</script>
</body>
</html>
Module-3 Javascript and DOM Manipulation
Subtraction Assignment (-=) Operator
The subtraction assignment operator in JavaScript subtracts the value of right operand from the left
operand and assigns the result to left operand (variable).
let x -=b;
<html>
<body>
<div id="output"></div>
<script>
let x = 15;
x -= 5;
</script>
</body>
</html>
let x *= b;
<html>
<body>
<div id="output"></div>
<script>
let x = 10;
x *= 5;
</script>
Module-3 Javascript and DOM Manipulation
</body>
</html>
let x /= b;
<html>
<body>
<div id="output"></div>
<script>
let x = 10;
x /= 5;
</script>
</body>
</html>
<html>
<body>
<div id="output"></div>
<script>
let x = 12;
x %= 5;
</body>
</html>
The JavaScript conditional (ternary) operator is only operator that takes three operands a condition
followed by a question mark (?), then the first expression to be executed if the condition is truthy
followed by a colon (:), and finally the second expression to be executed if the condition is falsy.
There are six falsy values in JavaScript. These are − 0 (zero), false, empty string ('' or ""), null,
undefined, and NaN. All other values are treated as truthy in JavaScript.
Syntax
Following is the syntax of conditional (ternary) operator in JavaScript −
Parameters
Here, we have explained the parameters in the above statement.
If the value of the condition is any falsy value, the result of the expression will be the value of exp2;
otherwise, it will be the value of exp1.
Example
In the example below, we compare the value of the num1 and num2 variables in the conditional
statement. Here, the conditional statement evaluates true, so the result variable contains the value of
the first expression.
<html>
<body>
Module-3 Javascript and DOM Manipulation
<div id="output"></div>
<script>
var res = num1 > num2 ? "num1 is greater than num2" : "num2 is greater than num1";
[Link]("output").innerHTML = res;
</script>
</body>
</html>
There are seven primitive or basic JavaScript data types: number, string, boolean, undefined, null,
symbol, and bigint. There is also a composite data type called object. The object data type contains
three sub data types Object, Array and Date.
typeof (operand);
typeof operand;
● Conditional Statements:-
1. JavaScript - if...else Statement
The JavaScript if...else statement executes a block of code when the specified condition is true.
When the condition is false the else block will be executed. The if-else statements can be used to
control the flow of execution of a program based on different conditions.
While writing a program, there may be a situation when you need to adopt one out of a given set of
paths. In such cases, you need to use conditional statements that allow your program to make
correct decisions and perform the right actions.
Module-3 Javascript and DOM Manipulation
JavaScript supports conditional statements used to perform different actions based on different
conditions. Here we will explain the if...else statement.
FlowChart of if-else
The following flow chart shows how the if-else statement works.
if statement
if...else statement
if...else if... statement.
JavaScript if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression) {
<html>
<body>
<div id ='output'> </div>
Module-3 Javascript and DOM Manipulation
<script type = "text/javascript">
let result;
let age = 20;
if( age > 18 ) {
result = "Qualifies for driving";
}
[Link]("output").innerHTML = result;
</script>
<p> Set the variable to a different value and then try... </p>
</body>
</html>
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the if
block, are executed. If the expression is false, then the given statement(s) in the else block are
executed.
Example
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<div id ='output'> </div>
<script type = "text/javascript">
let result;
let age = 15;
if( age > 18 ) {
result = "Qualifies for driving";
} else {
result = "Does not qualify for driving";
}
[Link]("output").innerHTML = result;
</script>
Module-3 Javascript and DOM Manipulation
<p> Set the variable to a different value and then try... </p>
</body>
</html>
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part of
the else clause of the previous statement. Statement(s) are executed based on the true condition, if
none of the conditions is true, then the else block is executed.
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<html>
<body>
<div id ="demo"></div>
<script type="text/javascript">
const output = [Link]("demo")
let book = "maths";
if (book == "history") {
[Link]="<b>History Book</b>";
} else if (book == "maths") {
[Link]="<b>Maths Book</b>";
} else if (book == "economics") {
[Link]="<b>Economics Book</b>";
} else {
[Link]="<b>Unknown Book</b>";
}
</script>
<p> Set the variable to a different value and then try... </p>
</body>
Module-3 Javascript and DOM Manipulation
<html>
Loop Statements:-
The purpose of a while loop is to execute a statement or code block repeatedly as long as an
expression is true. Once the expression becomes false, the loop terminates.
Flow Chart
The flow chart of while loop looks as follows −
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Example
In the example below, we defined the 'count' variable and initialized it with 0. After that, we make
iterations using the while loop until the value of the count is less than 10.
<html>
Module-3 Javascript and DOM Manipulation
<body>
<div id = 'output'></div>
<script type="text/javascript">
let output = [Link]("output");
var count = 0;
[Link]="Starting Loop <br>";
while (count < 10) {
[Link]+="Current Count : " + count + "<br>";
count++;
}
[Link]+="Loop stopped!";
</script>
<p> Set the variable to a different value and then try... </p>
</body>
</html>
Flow Chart
The flow chart of a do-while loop would be as follows −
Syntax
The syntax for do-while loop in JavaScript is as follows −
Module-3 Javascript and DOM Manipulation
do {
Statement(s) to be executed;
} while (expression);
Don't miss the semicolon used at the end of the do...while loop.
Example
In the example below, we used the do...while loop and printed the results in the output until the
value of the count variable is less than 5. In the output, we can observe that it always executes for
once, even if the condition is false.
<html>
<body>
<div id="output"></div>
<script type="text/javascript">
let output = [Link]("output");
var count = 0;
[Link] += "Starting Loop" + "<br />";
do {
[Link] += "Current Count : " + count + "<br />";
count++;
}
while (count < 5);
[Link] += "Loop stopped!";
</script>
<p>Set the variable to a different value and then try...</p>
</body>
</html>
3. JavaScript - For Loop
The JavaScript for loop is used to execute a block of code repeatedly, until a specified condition
evaluates to false. It can be used for iteration if the number of iteration is fixed and known.
The JavaScript loops are used to execute the particular block of code repeatedly. The 'for' loop is
the most compact form of looping. It includes the following three important parts
You can put all the three parts in a single line separated by semicolons.
Flow Chart
The flow chart of a for loop in JavaScript would be as follows −
Module-3 Javascript and DOM Manipulation
Syntax
The syntax of for loop is JavaScript is as follows −
Examples
Try the following examples to learn how a for loop works in JavaScript.
<html>
<head>
<title> JavaScript - for loop </title>
</head>
<body>
<p id = "output"> </p>
<script>
const output = [Link]("output");
[Link] = "Starting Loop <br>";
let count;
for (let count = 0; count < 10; count++) {
[Link] += "Current Count : " + count + "<br/>";
Module-3 Javascript and DOM Manipulation
}
[Link] += "Loop stopped!";
</script>
</body>
</html>
JavaScript - Break Statement
The break statement in JavaScript terminates the loop or switch case statement. When you use the
break statement with the loop, the control flow jumps out of the loop and continues to execute the
other code.
The break statement can also be used to jump a labeled statement when used within that labeled
statement. It is a useful tool for controlling the flow of execution in your JavaScript code.
Syntax
The syntax of break statement in JavaScript is as follows −
break;
OR
break [label];
Note In the next chapter, we will learn to use the break statement with the label inside the loop.
Flow Chart
The flow chart of a break statement would look as follows −
<html>
<head>
<title> JavaScript - Break statement </title>
</head>
<body>
<p id = "output"> </p>
<script>
const output = [Link]("output");
[Link] += "Entering the loop. <br /> ";
for (let x = 1; x < 10; x++) {
if (x == 5) {
break; // breaks out of loop completely
}
[Link] += x + "<br />";
}
[Link] += "Exiting the loop!<br /> ";
</script>
</body>
</html
JavaScript - Continue Statement
The continue statement in JavaScript is used to skip the current iteration of a loop and continue with
the next iteration. It is often used in conjunction with an if statement to check for a condition and
skip the iteration if the condition is met.
The JavaScript continue statement tells the interpreter to immediately start the next iteration of the
loop and skip the remaining code block. When a continue statement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise the control comes out of the loop.
Syntax
The syntax of continue statement in JavaScript is as follows −
continue;
OR
continue label;
We can use the continue statement inside the loops like for loop, while loop, dowhile loop, etc.
Module-3 Javascript and DOM Manipulation
We will learn to use the continue statement with the label statement in the upcoming chapter.
In the output, you can see that the code doesnt print 2 or 3.
Example
<html>
<head>
<title> JavaScript - Continue statement </title>
</head>
<body>
<p id = "output"> </p>
<script>
let output = [Link]("output");
var x = 1;
[Link] += "Entering the loop. <br /> ";
while (x < 5) {
x = x + 1;
if (x == 2 || x == 3) {
continue; // skip rest of the loop body
}
[Link] += x + "<br />";
}
[Link] += "Exiting the loop!<br /> ";
</script>
</body>
</html>
JavaScript - Switch Case
The JavaScript switch case is a conditional statement is used to execute different blocks of code
depending on the value of an expression. The expression is evaluated, and if it matches the value of
one of the case labels, the code block associated with that case is executed. If none of the case
labels match the value of the expression, the code block associated with the default label is
executed.
You can use multiple if...elseif statements, as in the previous chapter, to perform a multiway branch.
However, this is not always the best solution, especially when all of the branches depend on the
value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation,
and it does so more efficiently than repeated if...else if statements.
Module-3 Javascript and DOM Manipulation
Flow Chart
The following flow chart explains a switch-case statement works.
Advertisement
Syntax
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks each case against
the value of the expression until a match is found. If nothing matches, a default condition will be
used.
switch (expression) {
case condition 1: statement(s)
break;
default: statement(s)
}
Module-3 Javascript and DOM Manipulation
break − The statement keyword indicates the end of a particular case. If the 'break'
statement were omitted, the interpreter would continue executing each statement in each of
the following cases.
default − The default keyword is used to define the default expression. When any case
doesn't match the expression of the switch-case statement, it executes the default code
block.
Example
In the example below, we have a grade variable and use it as an expression of the switch case
statement. The switch case statement is used to execute the different code blocks according to the
value of the grade variable.
For the grade 'A', it prints the 'Good job' in the output and terminates the switch case statement as
we use the break statement.
<html>
<head>
<title> JavaScript - Switch case statement </title>
</head>
<body>
<p id = "output"> </p>
<script>
const output = [Link]("output");
let grade = 'A';
[Link] += "Entering switch block <br />";
switch (grade) {
case 'A': [Link] += "Good job <br />";
break;
case 'B': [Link] += "Passed <br />";
break;
case 'C': [Link] += "Failed <br />";
break;
default: [Link] += "Unknown grade <br />";
}
[Link] += "Exiting switch block";
</script>
</body>
</html>
● JavaScript - Functions
A function in JavaScript is a group of reusable code that can be called anywhere in your program.
It eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small and
manageable functions.
Module-3 Javascript and DOM Manipulation
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
All statements you need to execute on the function call must be written inside the curly braces.
Syntax:-
The basic syntax to define the function in JavaScript is as follows −
function functionName(parameter-list) {
statements
}
This type of function definition is called function declaration or function statement. We can also
define a function using function expression. We will discuss function expression in details in the
next chapter.
The following example defines a function called sayHello that takes no parameter −
function sayHello() {
alert("Hello there");
}
Function Expression
The Function expression in JavaScript allows you to define a function as an expression. The
function expression is similar to the anonymous function declaration. The function expression can
be assigned to a variable.
In the example below, we have defined a JavaScript function using function expression and
assigned it to a variable name myFunc.
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of that
function with the parentheses () as shown in the following code.
Module-3 Javascript and DOM Manipulation
Example
The below code shows the button in the output. When you click the button, it will execute the
sayHello() function. The sayHello() function prints the "Hello there!" message in the output.
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p> Use different text in the write method and then try... </p>
</body>
</html>
Function Parameters
Till now, we have seen functions without parameters. 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. A function can take multiple parameters
separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
[Link] (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
Module-3 Javascript and DOM Manipulation
</body>
</html>
Function with Default Parameters
For example, you can pass two numbers in a function, and then you can expect the function to
return their multiplication in your calling program.
Example
<html>
<head>
<script type="text/javascript">
function multiply(x, y) {
return x * y;
}
let result = multiply(4, 3);
[Link](result); // Output: 12
</script>
</head>
</html>
Function call()
With the call() method, you can write a method that can be used on different objects.
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function() {
[Link]("demo").innerHTML = [Link]();
</script>
</body>
</html>
Function bind()
With the bind() method, an object can borrow a method from another object.
The member object borrows the fullname method from the person object:
In the following example, the person object has a display method. In the display method, this refers to
Module-3 Javascript and DOM Manipulation
the person object:
This example will try to display the person name after 3 seconds, but it will display undefined instead:
In the following example, the bind() method is used to bind [Link] to person.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const person = {
firstName:"John",
lastName: "Doe",
fullName: function() {
return [Link] + " " + [Link];
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
[Link]("demo").innerHTML = fullName();
</script>
</body>
</html>
● SCOPE:-
Module-3 Javascript and DOM Manipulation
JavaScript variables can belong to:
Local Variables
A local variable is a "private" variable defined inside a function.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Local Scope</h1>
<p>Access a local variable defined inside a function:</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = myFunction();
function myFunction() {
let a = 4;
return a * a;
}
</script>
</body>
</html>
Global Variables
A global variable is a "public" variable defined outside a function.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
Module-3 Javascript and DOM Manipulation
<script>
let a = 4;
[Link]("demo").innerHTML = myFunction();
function myFunction() {
return a * a;
}
</script>
</body>
</html>
Global variables can be used (or changed) by all scripts in the page.
A local variable can only be used inside the function where it is defined. It is private and hidden from
other functions and other scripting code.
Global and local variables with the same name are different variables. Modifying one, does not modify
the other.
Undeclared variables (created without a keyword var, let, const), are always global, even if they are
created inside a function.
The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of a document as a tree of objects, where each object corresponds to a
part of the document, such as elements, attributes, and text. JavaScript can manipulate this tree
structure, allowing developers to dynamically alter the content and appearance of a
[Link] can interact with the DOM to dynamically change content, structure, and styles
on a webpage.
DOM Structure
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
DOM Manipulation
If you want to access any element in an HTML page, you always start with accessing the document
object.
Below are some examples of how you can use the document object to access and manipulate HTML.
Method Description
1. getElementById(id)
Module-3 Javascript and DOM Manipulation
<script>
var element = [Link]("demo");
[Link] = "blue"; // changes text color to blue
</script>
2. [Link](name)
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
var elements = [Link]("p");
elements[0].[Link] = "red"; // changes first paragraph color to red
elements[1].[Link] = "green"; // changes second paragraph color to green
</script>
3. [Link](name)
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<script>
var boxes = [Link]("box");
for (var i = 0; i < [Link]; i++) {
boxes[i].[Link] = "lightgray";
}
</script>
Property Description
Method Description
Example:-
Module-3 Javascript and DOM Manipulation
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Example</title>
</head>
<body>
<script>
// 1. [Link] - change the content
[Link]("title").innerHTML = "Updated Title using innerHTML";
// 4. [Link](attribute, value)
[Link]("myDiv").setAttribute("title", "This is a tooltip using
setAttribute");
</script>
</body>
</html>
Method Description
Example:-
<!DOCTYPE html>
<html>
<head>
<title>DOM Methods Example</title>
</head>
<body>
<div id="container">
<p id="para1">This is the original paragraph.</p>
</div>
<script>
// 1. [Link]()
var newPara = [Link]("p");
[Link] = "This is a new paragraph created with createElement.";
// 2. [Link]()
[Link]("container").appendChild(newPara);
// 3. [Link]()
var oldPara = [Link]("para1");
[Link]("container").removeChild(oldPara);
// 4. [Link]()
var replacement = [Link]("h3");
[Link] = "This <h3> replaced the new paragraph.";
[Link]("container").replaceChild(replacement, newPara);
// 5. [Link]()
[Link]("<hr><b>This is written using [Link]()</b>");
</script>
</body>
</html>
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
Module-3 Javascript and DOM Manipulation
onclick=JavaScript
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<script>
function displayDate() {
[Link]("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load
the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
<!DOCTYPE html>
<html>
<body onload="check()">
<p id="demo"></p>
<script>
function check() {
alert("page is load");
}
</script>
</body>
</html>
The oninput event is often to some action while the user input data.
Below is an example of how to use the oninput to change the content of an input field.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The oninput Attribute</h2>
The onchange event is often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user
changes the content of an input field.
<!DOCTYPE html>
Module-3 Javascript and DOM Manipulation
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onchange Attribute</h2>
<script>
function upperCase() {
const x = [Link]("fname");
[Link] = [Link]();
}
</script>
</body>
</html>
Mouse Events
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over,
or out of, an HTML element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript HTML Events</title>
</head>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onmouseover Attribute</h2>
<script>
function mOver(obj) {
[Link] = "Mouse Over";
}
function mOut(obj) {
[Link] = "Mouse Out";
Module-3 Javascript and DOM Manipulation
}
</script>
</body>
</html>
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a
mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released,
the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is
triggered.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onmousedown Attribute</h2>
<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:180px;height:200px;">
Click Me</div>
<script>
function mDown(obj) {
[Link] = "#1ec5e5";
[Link] = "mousedown";
}
function mUp(obj) {
[Link]="#D94A38";
[Link]="mouse up";
}
</script>
</body>
</html>
Form Submit Event
<form id="myForm">
<input type="text" id="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<script>
[Link]("myForm").addEventListener("submit", function(event) {
[Link](); // Prevent page reload
let name = [Link]("name").value;
alert("Form Submitted! Name: " + name);
});
</script>
Textbox Input Event
Module-3 Javascript and DOM Manipulation
<input type="text" id="username" placeholder="Type something...">
<p id="output"></p>
<script>
[Link]("username").addEventListener("input", function() {
[Link]("output").innerText = "You typed: " + [Link];
});
</script>
Focus Event
● The focus event fires when an element gains focus (e.g., when the user clicks inside an input
field).
● It is often used to highlight an input field or display hints when a user starts typing.
<p id="error"></p>
<script>
[Link]("blur", function() {
if () {
} else {
[Link] = "";
[Link] = "";
});
</script>
Keyboard events are used to detect when the user presses or releases keys on the keyboard.
Module-3 Javascript and DOM Manipulation
<div id="box" style="width: 50px; height: 50px; background: red; position: absolute;
top: 100px; left: 100px;"></div>
<script>
[Link] = y + "px";
[Link] = x + "px";
});
</script>
EventListener
The addEventListener() method
[Link]("myBtn").addEventListener("click", displayDate);
Module-3 Javascript and DOM Manipulation
The addEventListener() method attaches an event handler to the specified element.
The addEventListener() method attaches an event handler to an element without overwriting existing
event handlers.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for
better readability and allows you to add event listeners even when you do not control the HTML
markup.
You can easily remove an event listener by using the removeEventListener() method.
Syntax
The first parameter is the type of the event (like "click" or "mousedown" or any other HTML DOM
Event.)
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling or event capturing.
This parameter is optional.
[Link]("click", myFunction);
[Link]("click", mySecondFunction);
[Link]("mouseover", myFunction);
[Link]("click", mySecondFunction);
[Link]("mouseout", myThirdFunction);
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<style>
.error {
color: red;
font-size: 14px;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<form name="myForm" onsubmit="return validateForm()">
Name: <input type="text" name="name" id="name"><br>
<span id="nameError" class="error"></span><br>
Module-3 Javascript and DOM Manipulation
<script>
function validateForm() {
let name = [Link]("name").[Link]();
let email = [Link]("email").[Link]();
let password = [Link]("password").[Link]();
let phone = [Link]("phone").[Link]();
let emailPattern =
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/;
let phonePattern = /^[0-9]{10}$/;
let namePattern = /^[A-Za-z\s]+$/;
let passwordPattern = /^(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{6}$/;
// Validate Name
if (name === "") {
[Link]("nameError").innerHTML = "Name is
required";
isValid = false;
} else if () {
[Link]("nameError").innerHTML = "Only
characters allowed";
isValid = false;
}
// Validate Email
if () {
[Link]("emailError").innerHTML = "Enter a
valid email";
isValid = false;
}
// Validate Password
if () {
[Link]("passwordError").innerHTML =
"Password must be 6 characters, 1 digit, 1 uppercase";
isValid = false;
}
// Validate Phone
if () {
[Link]("phoneError").innerHTML = "Phone
must be 10 digits";
isValid = false;
}
Module-3 Javascript and DOM Manipulation
return isValid;
}
</script>
</body>
</html>
Advanced JavaScript:-
● Asynchronous Javascript:-
1)callbacks
A callback is a function passed as an argument to another [Link] a callback, you could call the
calculator function (myCalculator) with a callback (myCallback), and let the calculator function run
the callback after the calculation is finished:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>Callback Functions</h2>
<script>
function myDisplayer(something) {
[Link]("demo").innerHTML = something;
}
myCalculator(5, 5, myDisplayer);
</script>
</body>
</html>
2) Asynchronous
Functions running in parallel with other functions are called asynchronous.A good example is JavaScript
setTimeout().In the real world, callbacks are most often used with asynchronous functions.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>setTimeout() with a Callback</h2>
<h1 id="demo"></h1>
<script>
setTimeout(myFunction, 3000);
function myFunction() {
[Link]("demo").innerHTML = "I love You !!";
}
</script>
</body>
</html>
3000 is the number of milliseconds before time-out, so myFunction() will be called after 3 seconds.
Module-3 Javascript and DOM Manipulation
Instead of passing the name of a function as an argument to another function, you can always pass a whole
function instead:
In the example above, function(){ myFunction("I love You !!!"); } is used as a callback. It is a
complete function. The complete function is passed to setTimeout() as an argument.
3000 is the number of milliseconds before time-out, so myFunction() will be called after 3 seconds.
3) promises
A Promise contains both the producing code and calls to the consuming code:
When the producing code obtains the result, it should call one of the two callbacks:
When Call
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
[Link](
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
4) async/await
Async
Module-3 Javascript and DOM Manipulation
The keyword async before a function makes the function return a promise:
myFunction().then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Await Syntax
The await keyword can only be used inside an async function.
The await keyword makes the function pause the execution and wait for a resolved promise before it
continues:
We will not create them, but call one of them when the executor function is ready.
● Fetch API
😀
The Fetch API interface allows web browser to make HTTP requests to web servers.
<script>
getText("fetch_info.txt");
</body>
</html>
● AJAX Introduction
AJAX is a developer's dream, because you can:
Read data from a web server - after the page has loaded
Update a web page without reloading the page
Send data to a web server - in the background
The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This
means that it is possible to update parts of a web page, without reloading the whole page.
All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-in XMLHttpRequest
object.
Module-3 Javascript and DOM Manipulation
Syntax for creating an XMLHttpRequest object:
In this case, the callback function should contain the code to execute when the response is ready.
[Link] = function() {
Send a Request
To send a request to a server, you can use the open() and send() methods of the XMLHttpRequest
object:
[Link]("GET", "ajax_info.txt");
[Link]();
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<p>Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
[Link] = function() {
[Link]("demo").innerHTML = [Link];
}
[Link]("GET", "ajax_info.txt");
[Link]();
}
Module-3 Javascript and DOM Manipulation
</script>
</body>
</html>
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
open
Method Description
Property Description
The responseText property returns the server response as a JavaScript string, and you can use it
accordingly:
Example
[Link]("demo").innerHTML = [Link];
The responseXML property returns the server response as an XML DOM object.
Using this property you can parse the response as an XML DOM object:
Module-3 Javascript and DOM Manipulation
const xmlDoc = [Link];
●What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps
them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.
● HTML/DOM manipulation
● CSS manipulation
● HTML event methods
● Effects and animations
● AJAX
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice
that the <script> tag should be inside the <head> section):
<head>
<script src="[Link]"></script>
</head>
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the
element(s).
Examples:
ready
This is to prevent any jQuery code from running before the document is finished loading (is ready).
It is good practice to wait for the document to be fully loaded and ready before working with it. This
also allows you to have your JavaScript code before the body of your document, in the head section.
Here are some examples of actions that can fail if methods are run before the document is fully loaded:
●jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types,
attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition,
it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
$("p")
Example
$(document).ready(function(){
$("button").click(function(){
Module-3 Javascript and DOM Manipulation
$("p").hide();
});
});
An id should be unique within a page, so you should use the #id selector when you want to find a single,
unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML element:
$("#test")
Example
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
To find elements with a specific class, write a period character, followed by the name of the class:
$(".test")
Example
When a user clicks on a button, the elements with class="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
Module-3 Javascript and DOM Manipulation
});
});
❖ jQuery Event
What are Events?
All the different visitors' actions that a web page can respond to are called events.
Examples:
$(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully loaded.
This event is already explained in the jQuery Syntax chapter.
click()
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the current <p> element:
Example
$("p").click(function(){
$(this).hide();
Module-3 Javascript and DOM Manipulation
});
dblclick()
The function is executed when the user double-clicks on the HTML element:
Example
$("p").dblclick(function(){
$(this).hide();
});
mouseenter()
The function is executed when the mouse pointer enters the HTML element:
Example
$("#p1").mouseenter(function(){
});
mouseleave()
The function is executed when the mouse pointer leaves the HTML element:
$("#p1").mouseleave(function(){
});
mousedown()
The function is executed, when the left, middle or right mouse button is pressed down, while the mouse
is over the HTML element:
Module-3 Javascript and DOM Manipulation
Example
$("#p1").mousedown(function(){
});
mouseup()
The function is executed, when the left, middle or right mouse button is released, while the mouse is
over the HTML element:
Example
$("#p1").mouseup(function(){
});
hover()
The hover() method takes two functions and is a combination of the mouseenter() and mouseleave()
methods.
The first function is executed when the mouse enters the HTML element, and the second function is
executed when the mouse leaves the HTML element:
Example
$("#p1").hover(function(){
},
function(){
});
focus()
The focus() method attaches an event handler function to an HTML form field.
Module-3 Javascript and DOM Manipulation
The function is executed when the form field gets focus:
Example
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
blur()
The blur() method attaches an event handler function to an HTML form field.
Example
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
❖jQuery Effects
jQuery hide() and show()
With jQuery, you can hide and show HTML elements with the hide() and show() methods:
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
● fadeIn()
● fadeOut()
● fadeTo()
Syntax:
fadeIn
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
The following example demonstrates the fadeIn() method with different parameters:
Example
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
</head>
<body>
<div id="div1"
style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2"
style="width:80px;height:80px;display:none;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>
</body>
</html>
Syntax:
$(selector).fadeOut(speed);
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
<!DOCTYPE html>
<html>
<head>
<script src="[Link]
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
});
</script>
</head>
<body>
</body>
</html>
Module-3 Javascript and DOM Manipulation
The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).
Syntax:
fadeTo
The required speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value
between 0 and 1).
The optional callback parameter is a function to be executed after the function completes.
The following example demonstrates the fadeTo() method with different parameters:
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
● slideDown()
● slideUp()
Syntax:
$(selector).slideDown(speed);
Example
$("#flip").click(function(){
$("#panel").slideDown();
Module-3 Javascript and DOM Manipulation
});
Syntax:
$(selector).slideUp(speed);
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
$("#flip").click(function(){
$("#panel").slideUp();
});
❖jQuery HTML
Get Content - text(), html(), and val()
Three simple, but useful, jQuery methods for DOM manipulation are:
The following example demonstrates how to get content with the jQuery text() and html() methods:
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
Module-3 Javascript and DOM Manipulation
The following example demonstrates how to get the value of an input field with the jQuery val()
method:
$("#btn1").click(function(){
alert("Value: " + $("#test").val());
});
We will use the same three methods from the previous page to set content:
The following example demonstrates how to set content with the jQuery text(), html(), and val()
methods:
Example
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
We will look at four jQuery methods that are used to add new content:
The jQuery append() method inserts content AT THE END of the selected HTML elements.
Example
$("p").append("Some appended text.");
Module-3 Javascript and DOM Manipulation
jQuery prepend() Method
The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.
Example
$("p").prepend("Some prepended text.");
The jQuery after() method inserts content AFTER the selected HTML elements.
The jQuery before() method inserts content BEFORE the selected HTML elements.
jQuery has several methods for CSS manipulation. We will look at the following methods:
The following example shows how to add class attributes to different elements. Of course you can select
multiple elements, when adding classes:
$("button").click(function(){
$("#div1").addClass("important blue");
});
The following example shows how to remove a specific class attribute from different elements:
Example
$("button").click(function(){
$("h1, h2, p").removeClass("blue");
});
Example
$("button").click(function(){
$("h1, h2, p").toggleClass("blue");
});
To return the value of a specified CSS property, use the following syntax:
css("propertyname");
The following example will return the background-color value of the FIRST matched element:
$("p").css("background-color");
css("propertyname","value");
The following example will set the background-color value for ALL matched elements:
Example
$("p").css("background-color", "yellow");
css({"propertyname":"value","propertyname":"value",...});
The following example will set a background-color and a font-size for ALL matched elements: