0% found this document useful (0 votes)
4 views73 pages

Module 3

Module-3 covers the fundamentals of JavaScript and DOM manipulation, including variable declaration, scope, and operators. It explains client-side and server-side JavaScript, highlighting their roles in web applications. The module also details various operators such as arithmetic, comparison, logical, and bitwise operators, along with their usage and examples.

Uploaded by

sranjana18
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)
4 views73 pages

Module 3

Module-3 covers the fundamentals of JavaScript and DOM manipulation, including variable declaration, scope, and operators. It explains client-side and server-side JavaScript, highlighting their roles in web applications. The module also details various operators such as arithmetic, comparison, logical, and bitwise operators, along with their usage and examples.

Uploaded by

sranjana18
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

Module-3 Javascript and DOM Manipulation

●​ The basics of JavaScript


Overview of JavaScript, Object orientation and JavaScript, general Syntactic
characteristics, Primitives, operations, and expressions, Screen output and
keyboard input, Control statements, Object creation and modification, Arrays,
Functions, Constructors, Pattern matching using regular expressions, Errors in
scripts,
●​ JavaScript and HTML Documents
The JavaScript Execution Environment, The Document Object Model, Elements
Access in Java Script, Events and Event Handling, Handling Events from Body
Elements, Handling Events from Text Box and password Elements, The DOM2
Model, The navigator Object, Dom Tree Traversal and Modification.

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 – Client and Server Side

●​ 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

●​ Runs on the server.


●​ Used for file handling, database access, networking, and security tasks.
●​ Client-side JS cannot fully replace server-side functions.
●​ JavaScript Variables
Definition:

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:

JavaScript provides three keywords to declare variables:

1.​ var – Old way of declaring variables (function-scoped)


2.​ let – Introduced in ES6, block-scoped and preferred for variable declaration
3.​ const – Also introduced in ES6, used for declaring constants (cannot be reassigned)

Variable Declaration Keywords

JavaScript provides three ways to declare variables:

1. var (Old, function-scoped)

●​ Declares a variable that is function-scoped.​

●​ Can be redeclared and updated.​

●​ Gets hoisted (declared at the top of the function regardless of where it's written).

syntax:- var a = 10;

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).

●​ Can be updated but not redeclared in the same scope.​

●​ Also gets hoisted, but not initialized until code execution reaches the statement.
●​ syntax:- let b = 20;

Example:-

function greetUser() {

let name = "Daya";

[Link]("Hello, " + name);

greetUser(); // Output: Hello, Daya

[Link](name); // ❌ Error: name is not defined


3. const (Modern, block-scoped & constant)
●​ Block-scoped and read-only.

●​ Must be initialized at the time of declaration.


●​ Cannot be reassigned.
●​ syntax:- const PI = 3.14;

Example:-

const pi = 3.14159;

[Link]("Value of pi:", pi); // Output: 3.14159

// pi = 3.14; ❌ Error: Assignment to constant variable


Variable Naming Rules

●​ Must start with a letter, underscore _, or dollar sign $​

●​ Can contain letters, digits, _, and $​

●​ Case-sensitive​

●​ Cannot use reserved words like break, function, return, etc.

Dynamic Typing
Module-3 Javascript and DOM Manipulation
JavaScript is a dynamically typed language, meaning:

●​ The type of a variable is determined at runtime.​

●​ You can assign a different type of value to the same variable.

Ex:- let item = "book"; // string

item = 10; // now a number

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

[Link](x); // Error: x is not defined

●​ 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.

JavaScript supports the following types of operators.

​ 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 −

Operator Description Example

+ (Addition) Adds two operands. x + y will give 30.

Subtracts the second operand from


- (Subtraction) x - y will give -10.
the first.

* (Multiplication) Multiplies both operands. x * y will give 200.

Divides the numerator by the


/ (Division) y / x will give 2.
denominator.

Outputs the remainder of an


% (Modulus) y % x will give 0
integer division.

++ (Increment) Increases an integer value by one. x++ will give 11.

-- (Decrement) Decreases an integer value by one. x-- will give 9.

[Link] Comparison Operators


The comparison operators in JavaScript compare two variables or values and return a boolean
value, either true or false based on the comparison result. For example, we can use the comparison
operators to check whether two operands are equal or not.

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.

Operator Description Example

== Equal x == y

!= Not Equal x != y

=== Strict equality (equal value and equal type) x === y

!== Strict inequality (not equal value or not equal type) x !== y
Module-3 Javascript and DOM Manipulation
> Greater than x>y

< Less than x < y<

>= Greater than or Equal to x >= y

&lt= Less than or Equal to x &lt= y

[Link] Logical Operators


The logical operators in JavaScript are generally used with Boolean operands and return a boolean
value. There are mainly three types on logical operators in JavaScript - && (AND), || (OR), and !
(NOT). These operators are used to control the flow of the program.

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.

Operator Description Example

&& Logical AND (x && y) is false.

|| Logical OR (x || y) is true.

! Logical NOT !(x) is false.

JavaScript Logical AND (&&) Operator


The logical AND (&&) operator evaluates the operands from left to right. If the first operand can be
converted to false, it will return the value of the first operand, otherwise it will return the value of
the second operand.

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.

JavaScript Logical OR (||) Operator


The logical OR (||) operator also evaluates the operands from left to right. If the first operand can be
converted to true, it will return the value of first operand, otherwise it will return the value of the
second operand.

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.

JavaScript Logical NOT (!) Operator


The logical NOT (!) Operator is a unary operator. It returns false if the operand can be converted to
true, otherwise 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.

[Link] Bitwise Operators


The bitwise operators in JavaScript perform operations on the integer values at the binary level.
They are used to manipulate each bit of the integer values. Bitwise operators are similar to logical
operators but they work on individual bits.

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.

Operator Name Description


Module-3 Javascript and DOM Manipulation
& Bitwise AND Returns 1 if both bits are 1, otherwise 0.

| Bitwise OR Returns 1 if either bit is 1, otherwise 0.

^ Bitwise XOR Returns 1 if both bits are different, otherwise 0.

! Bitwise NOT Returns 1 if bit is 0, otherwise 0.

<< 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.

JavaScript Bitwise AND (&) Operator


The bitwise AND (&) operator performs AND operation on each pair of bits of its integer
operands. After the operation, it returns a new integer value with the updated 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;

[Link]("output").innerHTML = "a & b = " + (a & b);

</script>

</body>

</html>

JavaScript Bitwise OR (|) Operator


Module-3 Javascript and DOM Manipulation
The bitwise OR (|) operator performs OR operation on each pair of bits of its integer operands.
After the operation, it returns an integer value with the updated bits.

When bitwise OR operator is applied on a pair of bits, it returns 1 if either of bits is 1, otherwise
returns 0.

Following is the truth table for bitwise OR operation.

<html>

<body>

<div id="output"></div>

<script>

const a = 5;

const b = 7;

[Link]("output").innerHTML = "a | b = " + (a | b);

</script>

</body>

</html>

JavaScript Bitwise XOR (^) Operator


The bitwise XOR (^) operator performs an exclusive OR operation on each pair of bits of its integer
operands. After the operation, it returns an integer value with the updated bits.

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;

[Link]("output").innerHTML = "a ^ b = " + (a ^ b);

</script>
Module-3 Javascript and DOM Manipulation
</body>

</html>

JavaScript Bitwise NOT (~) Operator


The bitwise NOT (~) operator performs the NOT operation on each bit of the binary number. It is a
unary operator that inverts each bit of the binary number and returns the 2s complement to the
binary number.

<html>

<body>

<div id="output"></div>

<script>

const a = 5;

const b = 7;

[Link]("output").innerHTML =

"~a = " + (~a) + "<br>" +

"~b = " + (~b)

</script>

</body>

</html>

Bitwise Left Shift (<<) Operator


The JavaScript bitwise left shift (<<) operator moves all the bits in its first operand to the left by the
number of places specified in the second operand. New bits are filled with zeros from the right and
left; most bits are discarded.

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 =

"a << 1 = " + (a << 1) + "<br>" +

"a << 2 = " + (a << 2);

</script>

</body>

</html>

Bitwise Right Shift (>>) Operator


The bitwise right shift (>>) operator moves all the bits in its first operand to the right by the number
of places specified in the second operand. It inserts copies of the leftmost bit in from the left and
discards rightmost bits. In this way it preserves the sign of the number.

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 =

"a >> 1 = " + (a >> 1) + "<br>" +

"~a >> 1 = " + (~a >> 1);

</script>

</body>

</html>

Bitwise Right Shift with Zero (>>>) Operator


The Right Shift with Zero (>>>) operator is very similar to the right shift operator. It always fills
the left bits with zero without worrying about the sign of the bit.
Module-3 Javascript and DOM Manipulation
Example
Here, the binary representation of 10 is 1010. When we perform the right shift with zero operation,
it moves all bits 2 times in the right direction and inserts two 0's at the start. So, the resultant value
will be 0010, equal to 1.

<html>

<body>

<div id="output"></div>

<script>

const a = 5;

[Link]("output").innerHTML = "a >>> 1 = " + (a >>> 1);

</script>

</body>

</html>

[Link] Assignment Operators


The assignment operators in JavaScript are used to assign values to the variables. These are binary
operators. An assignment operator takes two operands, assigns a value to the left operand based on
the value of the right operand. The left operand is always a variable and the right operand may be
literal, variable or expression.

let x = 10; // right operand is a literal

let y = x; // right operand is a variable

let z = x + 10; // right operand is an expression

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.

Arithmetic Assignment Operators


Module-3 Javascript and DOM Manipulation
In this section, we will cover simple assignment and arithmetic assignment operators. An arithmetic
assignment operator performs arithmetic operations and assigns the result to a variable. Following
is the list of operators with example −

Assignment Operator Example Equivalent To

= (Assignment) a=b a=b

+= (Addition Assignment) a += b a=a+b

-= (Subtraction Assignment) a -= b a=ab

*= (Multiplication Assignment) a *= b a=a*b

/= (Division Assignment) a /= b a=a/b

%= (Remainder Assignment) a %= b a=a%b

**= (Exponentiation Assignment) a **= b a = a ** b

Addition Assignment (+=) Operator


The JavaScript addition assignment operator performs addition on the two operands and assigns the
result to the left operand. Here addition may be numeric addition or string concatenation.

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;

[Link]("output").innerHTML = "Value of x : " + x;

</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;

[Link]("output").innerHTML = "Value of x : " + x;

</script>

</body>

</html>

Multiplication Assignment (*=) Operator


The multiplication assignment operator in JavaScript multiplies the both operands and assign the
result to the left operand.

let x *= b;

<html>

<body>

<div id="output"></div>

<script>

let x = 10;

​ x *= 5;

[Link]("output").innerHTML = "Value of x : " + x;

</script>
Module-3 Javascript and DOM Manipulation
</body>

</html>

Division Assignment (/=) Operator


This operator divides left operand by the right operand and assigns the result to left operand.

let x /= b;

<html>

<body>

<div id="output"></div>

<script>

let x = 10;

x /= 5;

[Link]("output").innerHTML = "Value of x : " + x;

</script>

</body>

</html>

Remainder Assignment (%=) Operator


The JavaScript remainder assignment operator performs the remainder operation on the operands
and assigns the result to left operand.

<html>

<body>

<div id="output"></div>

<script>

let x = 12;

x %= 5;

[Link]("output").innerHTML = "Value of x : " + x;


Module-3 Javascript and DOM Manipulation
</script>

</body>

</html>

[Link] Conditional Operators


The conditional operator in JavaScript first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the evaluation. The
conditional operator is also known as the ternary operator.

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 −

var variable = condition ? exp1 : exp2;

Parameters
Here, we have explained the parameters in the above statement.

​ condition − It is a conditional statement.


​ exp1 − If the conditional statement evaluates truthy, control flow executes the exp1
expression.
​ exp2 − If the conditional statement evaluates falsy, control flow executes the exp2
expression.

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 num1 = 90;

var num2 = 67;

var res = num1 > num2 ? "num1 is greater than num2" : "num2 is greater than num1";

[Link]("output").innerHTML = res;

</script>

</body>

</html>

[Link] typeof Operator


The typeof operator in JavaScript is a unary operator used to get the data type of a particular
variable. It is placed before its single operand, which can be of any type. Its returns a string value
indicating the data type of its operand. JavaScript contains primitive and non-primitive data types.

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.

Following is the syntax of the typeof operator −

typeof (operand);

We can write the operand without parenthesis as follows −

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.

JavaScript supports the following forms of if...else statement −

​ 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) {

Statement(s) to be executed if expression is true

<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>

2.​ JavaScript if...else statement


The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.

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>

JavaScript if...else if... statement


The if...else if... statement (also called as if...else ladder)is an advanced form of ifelse that allows
JavaScript to make a correct decision out of several conditions.

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:-

1.​ JavaScript - While Loops


The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The
while loop is an entry-controlled loop.

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>

2.​ JavaScript do...while Loop


The do...while loop is similar to the while loop except that the condition check happens at the end
of the loop. This means that the loop will always be executed at least once, even if the condition is
false.

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

​ Initialization − The loop initialization expression is where we initialize our counter to a


starting value. The initialization statement is executed before the loop begins.
​ Condition − The condition expression which will test if a given condition is true or not. If
the condition is true, then the code given inside the loop will be executed. Otherwise, the
control will come out of the loop.
​ Iteration − The iteration expression is where you can increase or decrease your counter.

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 −

for (initialization; condition; iteration) {


Statement(s) to be executed if condition is true
}

Above all 3 statements are optional.

Examples
Try the following examples to learn how a for loop works in JavaScript.

Example: Executing a code block repeatedly


In the example below, we used the for loop to print the output's updated value of the 'count'
variable. In each iteration of the loop, we increment the value of 'count' by 1 and print in the output.

<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];

The label is optional with a break statement.

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 −

Example (break statement with for loop)


Module-3 Javascript and DOM Manipulation
In the example below, we used the for loop to make iterations. We added the conditional expression
in the loop using the 'if' statement. When the value of 'x' is 5, it will 'break' the loop using the break
statement.

The below code prints only 1 to 4 values in the output.

<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.

Continue statement with while loop


We used the while loop with the continue statement in the example below. In each iteration of the
while loop, we increment the x's value by 1. If the value of the x is equal to 2 or 3, it skips the
current iteration and moves to the next iteration.

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;

case condition 2: statement(s)


break;
...

case condition n: 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.

The syntax of function expression in JavaScript is as follows

const varName = function (parameter-list) {


statements
};

In the example below, we have defined a JavaScript function using function expression and
assigned it to a variable name myFunc.

const myFunc = function (x, y){


return x + y;
};

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

function greet(name = "Guest") {

[Link]("Hello, " + name);

greet(); // Output: Hello, Guest

greet("John"); // Output: Hello, John

The return Statement


A JavaScript function can have an optional return statement. This is required if you want to return
a value from a function. This statement should be the last statement in a function.

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.

In JavaScript all functions are object methods.

If a function is not a method of a JavaScript object, it is a function of the global object.

In JavaScript, the this keyword refers to an object.

The function above is actually an anonymous function (a function without a name).


Module-3 Javascript and DOM Manipulation
<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Functions</h2>

<p>This example creates an object with 3 properties (firstName, lastName, fullName).</p>

<p>The fullName property is a method:</p>

<p id="demo"></p>

<script>

const myObject = {

firstName:"John",

lastName: "Doe",

fullName: function() {

return [Link] + " " + [Link];

[Link]("demo").innerHTML = [Link]();

</script>

</body>

</html>

Function bind()

With the bind() method, an object can borrow a method from another object.

The example below creates 2 objects (person and member).

The member object borrows the fullname method from the person object:

Sometimes the bind() method has to be used to prevent losing this.

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:

When a function is used as a callback, this is lost.

This example will try to display the person name after 3 seconds, but it will display undefined instead:

The bind() method solves this problem.

In the following example, the bind() method is used to bind [Link] to person.

This example will display the person name after 3 seconds:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Function bind()</h1>

<p>This example creates 2 objects (person and member).</p>


<p>The member object borrows the fullname method from person:</p>

<p id="demo"></p>

<script>
const person = {
firstName:"John",
lastName: "Doe",
fullName: function() {
return [Link] + " " + [Link];
}
}

const member = {
firstName:"Hege",
lastName: "Nilsen",
}

let fullName = [Link](member);

[Link]("demo").innerHTML = fullName();
</script>

</body>
</html>
●​ SCOPE:-
Module-3 Javascript and DOM Manipulation
JavaScript variables can belong to:

The local scope or The global scope

Global variables can be made local (private) with closures.

Closures makes it possible for a function to have "private" variables.

Local Variables
A local variable is a "private" variable defined inside a function.

A function can access all variables in the local scope.

<!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.

A function can access all variables in the global scope:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Global Scope</h1>


<p>Access a global variable defined outside a function:</p>

<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>

In a web page, global variables belong to the page.

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.

DOM(Document Object Model)


What is DOM?

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:

The HTML DOM Tree of Objects


Module-3 Javascript and DOM Manipulation

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

●​ JavaScript can change all the HTML elements in the page


●​ JavaScript can change all the HTML attributes in the page
●​ JavaScript can change all the CSS styles in the page
●​ JavaScript can remove existing HTML elements and attributes
●​ JavaScript can add new HTML elements and attributes
●​ JavaScript can react to all existing HTML events in the page
●​ JavaScript can create new HTML events in the page

DOM Manipulation

The document object represents your web page.

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.

Finding HTML Elements

Method Description

[Link](id) Find an element by element id

[Link](name) Find elements by tag name

[Link](name) Find elements by class name

1.​ getElementById(id)
Module-3 Javascript and DOM Manipulation

<p id="demo">Hello World</p>

<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>

Changing HTML Elements

Property Description

[Link] = new html content Change the inner HTML of an element

[Link] = new value Change the attribute value of an HTML


element

[Link] = new style Change the style of an HTML element

Method Description

[Link](attribute, value) Change the attribute value of an HTML


element

Example:-
Module-3 Javascript and DOM Manipulation
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Example</title>
</head>
<body>

<h1 id="title">Original Title</h1>


<a id="myLink" href="[Link] Example</a>
<div id="myDiv">This is a box.</div>

<script>
// 1. [Link] - change the content
[Link]("title").innerHTML = "Updated Title using innerHTML";

// 2. [Link] - directly change an attribute


[Link]("myLink").href = "[Link]
[Link]("myLink").innerHTML = "Visit OpenAI";

// 3. [Link] - apply CSS styles


[Link]("myDiv").[Link] = "lightgreen";
[Link]("myDiv").[Link] = "10px";
[Link]("myDiv").[Link] = "2px solid green";

// 4. [Link](attribute, value)
[Link]("myDiv").setAttribute("title", "This is a tooltip using
setAttribute");
</script>

</body>
</html>

Adding and Deleting Elements

Method Description

[Link](element) Create an HTML element

[Link](element) Remove an HTML element

[Link](element) Add an HTML element

[Link](new, old) Replace an HTML element

[Link](text) Write into the HTML output stream


Module-3 Javascript and DOM Manipulation

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>

●​ JavaScript HTML DOM Events

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

Examples of HTML events:

●​ When a user clicks the mouse


●​ When a web page has loaded
●​ When an image has been loaded
●​ When the mouse moves over an element
●​ When an input field is changed
●​ When an HTML form is submitted
●​ When a user strokes a key
1.​ onclick():-

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>

<p>Click the button to display the date.</p>


<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
[Link]("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>

</body>
</html>

2.​ The onload and onunload Events

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()">

<h1>JavaScript HTML Events</h1>


Module-3 Javascript and DOM Manipulation
<h2>The onload Attribute</h2>

<p id="demo"></p>

<script>
function check() {
alert("page is load");
}
</script>

</body>
</html>

[Link] oninput Event

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>

Enter your name: <input type="text" id="fname" oninput="upperCase()">


<p>When you write in the input field, a function is triggered to transform the input to upper
case.</p>
<script>
function upperCase() {
const x = [Link]("fname");
[Link] = [Link]();
}
</script>
</body>
</html>

4. The onchange Event

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>

Enter your name: <input type="text" id="fname" onchange="upperCase()">


<p>When you leave the input field, a function transforms the input to upper case.</p>

<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>

<div onmouseover="mOver(this)" onmouseout="mOut(this)"


style="background-color:#D94A38;
cursor:pointer;">
Mouse Over Me
</div>

<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

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.

<input type="text" id="email" placeholder="Enter your email">

<p id="error"></p>

<script>

const emailInput = [Link]("email");

const error = [Link]("error");

[Link]("blur", function() {

if (![Link]("@")) {

[Link] = "Invalid email format!";

[Link] = "2px solid red";

} else {

[Link] = "";

[Link] = "";

});

</script>

Keyboard Events in JavaScript

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>

const box = [Link]("box");

let x = 100, y = 100;

[Link]("keydown", function (event) {

if ([Link] === "ArrowUp") y -= 10;

if ([Link] === "ArrowDown") y += 10;

if ([Link] === "ArrowLeft") x -= 10;

if ([Link] === "ArrowRight") x += 10;

[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 to one element.

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

[Link](event, function, useCapture);

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.

Add an Event Handler to an Element

Alert "Hello World!" when the user clicks on an element:

[Link]("click", function(){ alert("Hello World!"); });

You can also refer to an external "named" function:

Alert "Hello World!" when the user clicks on an element:


Module-3 Javascript and DOM Manipulation
[Link]("click", myFunction);
function myFunction() {
alert ("Hello World!");
}

Add Many Event Handlers to the Same Element


The addEventListener() method allows you to add many events to the same element, without
overwriting existing events:

[Link]("click", myFunction);
[Link]("click", mySecondFunction);

You can add events of different types to the same element:

[Link]("mouseover", myFunction);
[Link]("click", mySecondFunction);
[Link]("mouseout", myThirdFunction);

●​Form Validation Using Javascript

<!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

Email: <input type="text" name="email" id="email"><br>


<span id="emailError" class="error"></span><br>

Password: <input type="password" name="password"


id="password"><br>
<span id="passwordError" class="error"></span><br>

Phone: <input type="text" name="phone" id="phone"><br>


<span id="phoneError" class="error"></span><br><br>

<input type="submit" value="Submit">


</form>

<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}$/;

let isValid = true;

// Clear previous messages


[Link]("nameError").innerHTML = "";
[Link]("emailError").innerHTML = "";
[Link]("passwordError").innerHTML = "";
Module-3 Javascript and DOM Manipulation
[Link]("phoneError").innerHTML = "";

// Validate Name
if (name === "") {
[Link]("nameError").innerHTML = "Name is
required";
isValid = false;
} else if (![Link](name)) {
[Link]("nameError").innerHTML = "Only
characters allowed";
isValid = false;
}

// Validate Email
if (![Link](email)) {
[Link]("emailError").innerHTML = "Enter a
valid email";
isValid = false;
}

// Validate Password
if (![Link](password)) {
[Link]("passwordError").innerHTML =
"Password must be 6 characters, 1 digit, 1 uppercase";
isValid = false;
}

// Validate Phone
if (![Link](phone)) {
[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>

<p>The result of the calculation is:</p>


<p id="demo"></p>

<script>
function myDisplayer(something) {
[Link]("demo").innerHTML = something;
}

function myCalculator(num1, num2, myCallback) {


let sum = num1 + num2;
myCallback(sum);
}

myCalculator(5, 5, myDisplayer);
</script>

</body>
</html>

In the example above, myDisplayer is a called a callback function.

It is passed to myCalculator() as an argument.


Module-3 Javascript and DOM Manipulation
When you pass a function as an argument, remember not to use parenthesis.

Right: myCalculator(5, 5, myDisplayer);

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.

A typical example is JavaScript setTimeout().

Waiting for a Timeout


When using the JavaScript function setTimeout(), you can specify a callback function to be executed on
time-out:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>setTimeout() with a Callback</h2>

<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>

<h1 id="demo"></h1>

<script>
setTimeout(myFunction, 3000);

function myFunction() {
[Link]("demo").innerHTML = "I love You !!";
}
</script>

</body>
</html>

In the example above, myFunction is used as a callback.

myFunction is passed to setTimeout() as an argument.

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:

setTimeout(function() { myFunction("I love You !!!"); }, 3000);


function myFunction(value) {
[Link]("demo").innerHTML = value;
}

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

"Producing code" is code that can take some time

"Consuming code" is code that must wait for the result

A Promise contains both the producing code and calls to the consuming code:

let myPromise = new Promise(function(myResolve, myReject) {


// "Producing Code" (May take some time)

myResolve(); // when successful


myReject(); // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)


[Link](
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);

When the producing code obtains the result, it should call one of the two callbacks:

When Call

Success myResolve(result value)

Error myReject(error object)


Here is how to use a Promise:
[Link](
Module-3 Javascript and DOM Manipulation
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
[Link]() takes two arguments, a callback for success and another for failure.
Both are optional, so you can add a callback for success or failure only.
Example:-
function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}

let myPromise = new Promise(function(myResolve, myReject) {


let x = 0;

// The producing code (this may take some time)

if (x == 0) {
​ myResolve("OK");
} else {
​ myReject("Error");
}
});

[Link](
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);

JavaScript Promise Examples


To demonstrate the use of promises, we will use the callback examples from the previous chapter:

●​ Waiting for a Timeout

setTimeout(function() { myFunction("Welcome !!!"); }, 3000);


function myFunction(value) {
[Link]("demo").innerHTML = value;
}

4) async/await

Async
Module-3 Javascript and DOM Manipulation
The keyword async before a function makes the function return a promise:

async function myFunction() {


return "Hello";
}

Here is how to use the 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:

let value = await promise;


async function myDisplay() {
let myPromise = new Promise(function(resolve, reject) {
resolve("welcome");
[Link]("demo").innerHTML = await myPromise;
}
myDisplay();

The two arguments (resolve and reject) are pre-defined by JavaScript.

We will not create them, but call one of them when the executor function is ready.

Very often we will not need a reject function.

async function myDisplay() {


let myPromise = new Promise(function(resolve) {
​ resolve("Welcome");
});
[Link]("demo").innerHTML = await myPromise;
}
myDisplay();

●​ Fetch API

😀
The Fetch API interface allows web browser to make HTTP requests to web servers.

No need for XMLHttpRequest anymore.


Module-3 Javascript and DOM Manipulation
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>

<script>
getText("fetch_info.txt");

async function getText(file) {


let myObject = await fetch(file);
let myText = await [Link]();
[Link]("demo").innerHTML = myText;
}
</script>

</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


The keystone of AJAX is the XMLHttpRequest object.

1.​ Create an XMLHttpRequest object


2.​ Define a callback function
3.​ Open the XMLHttpRequest object
4.​ Send a Request to a server

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

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.

Create an XMLHttpRequest Object

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:

variable = new XMLHttpRequest();

Define a Callback Function

A callback function is a function passed as a parameter to another function.

In this case, the callback function should contain the code to execute when the response is ready.

[Link] = function() {

// What to do when the response is ready

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>

<h2>The XMLHttpRequest Object</h2>

<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>

Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

open

Method Description

open(method, url, async) Specifies the type of request

method: the type of request: GET or POST


url: the server (file) location
async: true (asynchronous) or false (synchronous)

send() Sends the request to the server (used for GET)

send(string) Sends the request to the server (used for POST)

AJAX-Server Response Properties

Property Description

responseText get the response data as a string

responseXML get the response data as XML data

The responseText Property

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

The XMLHttpRequest object has an in-built XML parser.

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.

The jQuery library contains the following features:

●​ 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).

Basic syntax is: $(selector).action()

●​ A $ sign to define/access jQuery


●​ A (selector) to "query (or find)" HTML elements
●​ A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.


Module-3 Javascript and DOM Manipulation
$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

The Document Ready Event


You might have noticed that all jQuery methods in our examples, are inside a document ready event:

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:

●​ Trying to hide an element that is not created yet


●​ Trying to get the size of an image that is not loaded yet

●​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: $().

The element Selector


The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

When a user clicks on a button, all <p> elements will be hidden:

Example

$(document).ready(function(){

$("button").click(function(){
Module-3 Javascript and DOM Manipulation
​ $("p").hide();

});

});

The #id Selector


The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

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();

});

});

The .class Selector


The jQuery .class selector finds elements with a specific class.

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
});

});

$("*") Selects all elements

$(this) Selects the current HTML element

❖​ jQuery Event
What are Events?

All the different visitors' actions that a web page can respond to are called events.

An event represents the precise moment when something happens.

Examples:

●​ moving a mouse over an element


●​ selecting a radio button
●​ clicking on an element

Commonly Used jQuery Event Methods

$(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 click() method attaches an event handler function to an HTML element.

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 dblclick() method attaches an event handler function to an HTML element.

The function is executed when the user double-clicks on the HTML element:

Example
$("p").dblclick(function(){

$(this).hide();

});

mouseenter()

The mouseenter() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer enters the HTML element:

Example
$("#p1").mouseenter(function(){

alert("You entered p1!");

});

mouseleave()

The mouseleave() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer leaves the HTML element:

$("#p1").mouseleave(function(){

alert("Bye! You now leave p1!");

});

mousedown()

The mousedown() method attaches an event handler function to an HTML element.

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(){

alert("Mouse down over p1!");

});

mouseup()

The mouseup() method attaches an event handler function to an HTML element.

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(){

alert("Mouse up over p1!");

});

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(){

alert("You entered p1!");

},

function(){

alert("Bye! You now leave p1!");

});

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.

The function is executed when the form field loses focus:

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>

jQuery Fading Methods


Module-3 Javascript and DOM Manipulation
With jQuery you can fade an element in and out of visibility.

jQuery has the following fade methods:

●​ fadeIn()
●​ fadeOut()
●​ fadeTo()

jQuery fadeIn() Method

The jQuery fadeIn() method is used to fade in a hidden element.

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>

<p>Demonstrate fadeIn() with different parameters.</p>

<button>Click to fade in boxes</button><br><br>


Module-3 Javascript and DOM Manipulation

<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>

jQuery fadeOut() Method

The jQuery fadeOut() method is used to fade out a visible element.

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>

<p>Demonstrate fadeOut() with different parameters.</p>

<button>Click to fade out boxes</button><br><br>

<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>


<div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

</body>
</html>
Module-3 Javascript and DOM Manipulation

jQuery fadeTo() Method

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);
});

jQuery Sliding Methods

With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

●​ slideDown()
●​ slideUp()

jQuery slideDown() Method

The jQuery slideDown() method is used to slide down an element.

Syntax:

$(selector).slideDown(speed);

Example
$("#flip").click(function(){

$("#panel").slideDown();
Module-3 Javascript and DOM Manipulation
});

jQuery slideUp() Method

The jQuery slideUp() method is used to slide up an element.

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 following example demonstrates the slideUp() method:

The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.

The following example demonstrates the slideDown() method:

$("#flip").click(function(){

$("#panel").slideUp();

});

❖​jQuery HTML
Get Content - text(), html(), and val()

Three simple, but useful, jQuery methods for DOM manipulation are:

●​ text() - Sets or returns the text content of selected elements


●​ html() - Sets or returns the content of selected elements (including HTML markup)
●​ val() - Sets or returns the value of form fields

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());
});

Set Content - text(), html(), and val()

We will use the same three methods from the previous page to set content:

●​ text() - Sets or returns the text content of selected elements


●​ html() - Sets or returns the content of selected elements (including HTML markup)
●​ val() - Sets or returns the value of form fields

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");
});

Add New HTML Content

We will look at four jQuery methods that are used to add new content:

●​ append() - Inserts content at the end of the selected elements


●​ prepend() - Inserts content at the beginning of the selected elements
●​ after() - Inserts content after the selected elements
●​ before() - Inserts content before the selected elements
●​

jQuery append() Method

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.");

jQuery after() and before() Methods

The jQuery after() method inserts content AFTER the selected HTML elements.

The jQuery before() method inserts content BEFORE the selected HTML elements.

$("img").after("Some text after");


$("img").before("Some text before");

❖​jQuery - Get and Set CSS Classes


jQuery Manipulating CSS

jQuery has several methods for CSS manipulation. We will look at the following methods:

●​ addClass() - Adds one or more classes to the selected elements


●​ removeClass() - Removes one or more classes from the selected elements
●​ toggleClass() - Toggles between adding/removing classes from the selected elements
●​ css() - Sets or returns the style attribute

jQuery addClass() Method

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");
});

jQuery removeClass() Method

The following example shows how to remove a specific class attribute from different elements:

Example
$("button").click(function(){
$("h1, h2, p").removeClass("blue");
});

jQuery toggleClass() Method


Module-3 Javascript and DOM Manipulation
The following example will show how to use the jQuery toggleClass() method. This method toggles
between adding/removing classes from the selected elements:

Example
$("button").click(function(){
$("h1, h2, p").toggleClass("blue");
});

❖​ jQuery css() Method


The css() method sets or returns one or more style properties for the selected elements.

Return a CSS Property

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");

Set a CSS Property

To set a specified CSS property, use the following syntax:

css("propertyname","value");

The following example will set the background-color value for ALL matched elements:

Example
$("p").css("background-color", "yellow");

Set Multiple CSS Properties

To set multiple CSS properties, use the following syntax:

css({"propertyname":"value","propertyname":"value",...});

The following example will set a background-color and a font-size for ALL matched elements:

$("p").css({"background-color": "yellow", "font-size": "200%"});


Module-3 Javascript and DOM Manipulation

You might also like