0% found this document useful (0 votes)
6 views41 pages

Java Script

JavaScript is a client-side programming language primarily used for web development, enabling dynamic updates to HTML and CSS. It was created by Netscape and is distinct from Java, as it is interpreted in the browser rather than compiled. The document covers fundamental concepts of JavaScript, including variables, data types, and how to include JavaScript in HTML.

Uploaded by

santoshpuhan09
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)
6 views41 pages

Java Script

JavaScript is a client-side programming language primarily used for web development, enabling dynamic updates to HTML and CSS. It was created by Netscape and is distinct from Java, as it is interpreted in the browser rather than compiled. The document covers fundamental concepts of JavaScript, including variables, data types, and how to include JavaScript in HTML.

Uploaded by

santoshpuhan09
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

Introduction to

JavaScript
Dr. Indrajeet Kumar

What is JavaScript?

 JavaScript is the programming


language of the web.

 It can update and change both HTML


and CSS.

 It can calculate, manipulate, and


validate data.

208

What is JavaScript?
 Created by Netscape
 Originally called LiveWire then LiveScript

 A client-side scripting language


 Client-side refers to the fact that it is executed in the client
(software) that the viewer is using. In the case of JavaScript,
the client is the browser.
 A server-side language is one that runs on the Web server.
Examples: PHP, Python.

 Interpreted on-the-fly by the client


 Each line is processed as it loads in the browser

209

1
JavaScript is not Java

 Completely different types of languages that


just happen to be similarly named

 JavaScript - programs are interpreted in


the browser
 Java - programs are compiled and can be
run as standalone applications.

210

Why JavaScript?

 It’s easier to learn than most programming languages.

 It allows you to make interactive Web pages.

211

Including JavaScript in HTML


 Two ways to add JavaScript to Web pages

 Use the <script>…</script> tag


 Include the script in an external file.

 Initially, we will only use the <script>…</script> tag

212

2
Hello, World!

 Typically, in any programming language,


the first example you learn displays
“Hello, World!”.

 We are going to take a look at a Hello


World example and then examine all of
its parts.

213

Hello World in JavaScript


<!DOCTYPE html>
<html>
<head>
<title>Hello World Example</title>
</head>
<body>
<script type="text/javascript">
<
[Link]("<h1>Hello, world!</h1>");
//-->
</script>
</body>
</html>
214

Hello World Screenshot

215

3
The <script>…</script> tag

 The code for the script is contained in the <script>…</script> tag

<script type="text/javascript">
.
.
.
</script>
216

Hiding JavaScript from Older


Browsers
 Some older browsers do not support JavaScript
 We need to tell those browsers to ignore what is in the
<script> tag

<script type="text/javascript">
<!--
some JavaScript code
//-->
</script>
217

Displaying text
 The [Link]() method writes a string of text to the browser

<script type="text/javascript">
<!--
[Link]("<h1>Hello, world!</h1>");

//-->
</script>

218

4
[Link]()

Ends in a semicolon

[Link]("<h1>Hello,world!</h1>");

Enclosed in quotes --
denotes a "string"

219

Comments in JavaScript

 Two types of comments


 Single line
 Uses two forward slashes (i.e. //)

 Multiple line
 Uses /* and */

220

Single Line Comment


Example

<script type="text/javascript">
<!--
// This is my JavaScript comment
[Link]("<h1>Hello!</h1>");
//-->
</script>

221

5
Multiple Line Comment
Example

<script type="text/javascript">
<!--
/* This is a multiple line comment.
* The star at the beginning of this line is optional.
* So is the star at the beginning of this line.
*/
[Link]("<h1>Hello!</h1>");
//-->
</script>

222

Variables

 A variable is a name associated with a piece


of data

 Variables allow you to store and manipulate


data in your programs

 Think of a variable as a mailbox which holds a


specific piece of information

Variables
 In JavaScript, variables
are created using the
keyword var  Example:

var x = 10;

var y = 17;

var color = “red”;

var name = “Katie”;

6
Variables

 It is vitally important to distinguish between the name of


the variable and the value of the variable.

 For example, in the expression var color=“red”,


color is the name of the variable and red is the value.

 In other words, color is the name of the box while red is


what is inside the box

Parameters Var Let

Var has been a part of Let was introduced in


Introduction in
JavaScript since its the ES 2015 (ES6)
JavaScript
inception. version of JavaScript.

Scope Var is globally scoped. Let is block-scoped.

Let can be declared


globally, but its
Access and Var can be declared and
access is limited to
Declaration accessed globally.
the block in which it
is declared.

Variables declared
Variables declared using
with let can be
var can be re-declared
Redeclaration updated but not re-
and updated within the
declared within the
same scope.
same scope.
226

var let const


The scope of a var The scope of a let The scope of a const
variable is functional variable is block variable is block
or global scope. scope. scope.
It can be updated and It can be updated but It can neither be
re-declared in the cannot be re-declared updated or re-
same scope. in the same scope. declared in any scope.

It can be declared It can be declared It cannot be declared


without initialization. without initialization. without initialization.

It cannot be accessed
It can be accessed It cannot be accessed
without initialization,
without initialization without initialization
as it cannot be
as its default value is otherwise it will give
declared without
“undefined”. ‘referenceError’.
initialization.
These variables are These variables are
hoisted but stay in the hoisted but stays in
These variables are
temporal dead zone the temporal dead
hoisted.
untill the zone until the
initialization. initialization.
227

7
Example
var a = 10
Output
function f()
10 20
{
10
var b = 20
[Link](a, b)
}
f();
[Link](a);

228

function f()
{ Output:

// It can be accessible any 10


// where within this function
Reference Error: a is not defined
var a = 10;
[Link](a)
var a = 10
}
f(); // User can re-declare
// variable using var
// A cannot be accessible var a = 8
// outside of function // User can update var variable
[Link](a); a=7
[Link](a);

229

Example (let)
let a = 10;
let a = 10; function f() {
if (true) {
function f() let b = 9
{ [Link](b);
}
let b = 9
[Link](b);
[Link](b); }
[Link](a); f()

} [Link](a)
f();

Output Output:

9 9

10 ReferenceError: b is not defined


230

8
let a = 10 /*behaviour of let variables when they are re-
declared in the different scopes.*/
// It is not allowed
let a = 10 let a = 10
if (true) {
// It is allowed let a = 9
a = 10 [Link](a) // It prints 9
}
[Link](a) // It prints 10

Output
Output:
9
Uncaught SyntaxError: Identifier 'a'
10
has already been declared

[Link](a);
let a = 10;

231

Example (const)
//This code explains the use of the const
//This code tries to change the keyword to declare the JavaScript objects.
value of the const variable.
const a =
const a = 10; {
function f() { prop1: 10,
prop2: 9
a=9 }
[Link](a) // It is allowed
} a.prop1 = 3

f(); // It is not allowed


a={
Output: b: 10,
prop2: 9
Type Error: Assignment to constant }
variable.

232

Data Types

 Primitive Data Types


 Numbers
 Strings
 Boolean (True, False)

 Composite Data Types


 Arrays
 Objects

9
Primitive Data Types
 Numbers - A number can be either an integer or a
decimal

 Strings - A string is a sequence of letters or numbers


enclosed in single or double quotes

 Boolean - True or False

Variables & Data Types

 JavaScript is untyped; It does not have explicit data


types.

 For instance, there is no way to specify that a


particular variable represents an integer, string, or
real number.

 The same variable can have different data types in


different contexts

Implicit Data Types

 Although JavaScript does not have explicit data types, it


has implicit ones.

 If you have an expression that combines two numbers, it


will evaluate to a number.

 If you have an expression that combines a string and a


number, it will evaluate a string.

10
Example: Variables

var x = 4; Ans = x + y;
Ans => 15
var y = 11;
Ans = z + x;
var z = “cat”; Ans => cat4

var q = “17”; Ans = x + q;


Ans => 417

More Examples

var x = 4; Ans = x + y + z;
Ans => 15cat
var y = 11;
Ans = q + x + y;
var z = “cat”; Ans => 17411

var q = “17”;

let n1 = 2; let s1 = "Hello There";


[Link](n1) [Link](s);
let n2 = 1.3;
[Link](n2) let s2 = 'Single quotes work
fine';
let n3 = Infinity;
[Link](s1);
[Link](n3)
let n4 = 'something here too'2;
let s3 = `can embed ${s1}`;
[Link](n4)
[Link](s3);

OUTPUT Output
2 Hello There
1.3 Single quotes work fine
Infinity can embed Hello There
NaN

239

11
let b1 = true; let age = null;
[Link](b1); [Link](age)

let b2 = false; Output


[Link](b2);
null
Output
let a;
[Link](a);
true
Output
false
undefined

240

Arrays

 An array is a compound data type that stores numbered


pieces of data.

 Each numbered datum is called an element of the array


and the number assigned to it is called an index.

 The elements of an array may be of any type. A single


array can even store elements of different type.

Creating an Array

 There are several different ways to create an array in


JavaScript.
 Using the Array() constructor:

- var a = new Array(1, 2, 3, 4, 5);


- var b = new Array(10);
 Using array literals:
- var c = [1, 2, 3, 4, 5];

12
Accessing Array Elements

 Array elements are accessed using the [ ] operator.


 Example:
 var colors = [“red”, “green”, “blue”];
 colors[0] => red
 colors[1] => green

Adding Elements

 To add a new element to an array, simply assign a value


to it.
 Example:
var a = new Array(10);
a[50] = 17;

Array Length

 All arrays created in JavaScript have a special length


property that specifies how many elements the array
contains
 Example:
 var colors = [“red”, “green”, “blue”];
 [Link] => 3

13
JavaScript Arrays
 An array is a special variable, which can hold
more than one value:
const cars = ["Saab", "Volvo", "BMW"];

 Syntax:
 const array_name = [item1, item2, ...];
 const cars = ["Saab", "Volvo", "BMW"];

 Syntax:
cars = ["Saab", "Volvo", "BMW"];
var cars;

246

<html> <body>
<h1>JavaScript Arrays</h1>
<h2>Declaring an Array Using const</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
{
const cars = ["Toyota", "Volvo", "BMW"];
}
[Link]("demo").innerHTML = cars[0];
</script>
</body>
</html>

247

let x = 42;
//[Link](x);
x = "hello";
//[Link](x);
x = [1, 2, 3];
[Link](x)

Output
42
hello
[ 1, 2, 3 ]

248

14
JavaScript Object Literal
 An object literal is a list of
property names:values inside curly
braces {}.
 {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};

 Note: An object literal is also called


an object initializer.

 // Create an Object
const person = {};
249

Creation using Object Literal: The object literal


syntax allows you to define and initialize an object
with curly braces {}, setting properties as key-
value pairs.

let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
[Link](obj);

Output

{ name: 'Sourav', age: 23, job: 'Developer' }


250

Creation Using new Object() Constructor

let obj = new Object();


[Link]= "Sourav",
[Link]= 23,
[Link]= "Developer"
[Link](obj);

Output

{ name: 'Sourav', age: 23, job: 'Developer' }

251

15
Operations on JavaScript Objects
Accessing Object Properties
let obj = { name: "Sourav", age: 23 };
// Using Dot Notation
[Link]([Link]);
// Using Bracket Notation
[Link](obj["age"]);

Output
Sourav
23
252

Modifying Object Properties: Properties in an object


can be modified by reassigning their values.

let obj = { name: "Sourav", age: 22 };


[Link](obj);

[Link] = 23;
[Link](obj);

Output

{ name: 'Sourav', age: 22 }


{ name: 'Sourav', age: 23 }
253

Adding Properties to an Object: You can dynamically


add new properties to an object using dot or bracket
notation.

let obj = { model: "Tesla" };


[Link] = "Red";
[Link](obj);

Output

{ model: 'Tesla', color: 'Red' }

254

16
Removing Properties from an Object:
The delete operator removes properties from an
object.

let obj = { model: "Tesla", color: "Red" };


delete [Link];
[Link](obj);

Output

{ model: 'Tesla' }

255

Checking if a Property Exists:


You can check if an object has a property using the in
operator or hasOwnProperty() method.

let obj = { model: "Tesla" };


[Link]("color" in obj);
[Link]([Link]("model"));

Output
false
true

256

Iterating Through Object Properties

Use for…in loop to iterate through the properties of


an object.

let obj = { name: "Sourav", age: 23 };


for (let key in obj)
{
[Link](key + ": " + obj[key]);
}
Output
name: Sourav
age: 23
257

17
Merging Objects
Objects can be merged using [Link]() or the spread
syntax { …obj1, …obj2 }.

let obj1 = { name: "Sourav" };


let obj2 = { age: 23};
let obj3 = { ...obj1, ...obj2 };
[Link](obj3);

Output
{ name: 'Sourav', age: 23 }

258

Object Length

You can find the number of properties in an object using


[Link]().

let obj = { name: "Sourav", age: 23 };


[Link]([Link](obj).length);

Output
2

259

Primitive Data Types versus


Composite Data Types
 Variables for primitive data types hold the actual value
of the data.

 Variables for composite types hold only references to


the values of the composite type.

18
Variable Names

 JavaScript is case sensitive


 Variable names cannot contain spaces, punctuation, or
start with a digit
 Variable names cannot be reserved words

Operators

+ Addition = = Equality
- Subtraction ! = Inequality
* Multiplication ! Logical NOT
/ Division &&Logical AND
% Modulus || Logical OR
++ Increment ? Conditional
Selection
-- Decrement

Aggregate Assignments

 Aggregate assignments provide a shortcut by


combining the assignment operator with some
other operation

 The += operator performs addition and assignment

 The expression x = x + 7 is equivalent to the


expression x += 7

19
Increment and Decrement

 Both the increment (++) x = 10; x = 10;


and decrement (- -)
y = ++ x; z = x ++;
operator come in two
forms: prefix and
postfix.  y = 11
 z = 10
 These two forms yield  x = 11 in both cases
different results

Control Structures

 There are three basic types of control structures in


JavaScript: the if statement, the while loop, and the
for loop.

 Each control structure manipulates a block of JavaScript


expressions beginning with { and ending with }

The If Statement

 The if statement allows If ( x = = 10)


JavaScript programmers
{ y = x*x;
to a make decision.
}
else
 Use an if statement
whenever you come to a { x = 0;
“fork” in the program. }

20
Repeat Loops
 A repeat loop is a group of statements that is repeated
until a specified condition is met.

 Repeat loops are very powerful programming tools;


They allow for more efficient program design and are
ideally suited for working with arrays.

 There are mainly two types of loops.


• Entry Controlled loops: For Loop and While Loops are
entry-controlled loops.
• Exit Controlled Loops: do-while loop

The While Loop


 The while loop is used to count = 0;
execute a block of code
while (count <= 10) {
while a certain condition
is true [Link](count);
count++;
}

let arr = [10, 20, 30, 40]; let count = 1;


let i = 0; while (count <= 5)
while (i < [Link]) {
{ [Link](count);
count++;
[Link](arr[i]);
}
i++;
}

269

21
The For Loop
 The for loop is used when there is
a need to have a counter of some
kind.
 The counter is initialized before
the loop starts, tested after each
iteration to see if it is below a
target value, and finally updated
at the end of the loop.

Example: For Loop

// Print the numbers 1 i=1 initializes the counter


through 10

i<=10 is the target


for (i=1; i<= 10; i++)
value
[Link](i);

i++updates the
counter at the end
of the loop

Example: For Loop

<SCRIPT <SCRIPT
LANGUAGE= LANGUAGE=
"JavaScript"> "JavaScript">
[Link]("1");
[Link]("2");
for (i=1; i<=5; i++)
[Link]("3");
[Link](i);
[Link]("4");
[Link]("5");
</SCRIPT>

22
for (let i = 1; i <= 3; i++)
{
[Link]("Count:", i);
}

273

do…while Loop
Syntax: Example:
do { let test = 1;
// Statements do
} {
while(conditions) [Link](test);
test++;
}
while(test<=5)

274

do…while while
It is an exit-controlled It is an entry-controlled
loop loop.
The number of
The number of
iterations will be at
iterations depends upon
least one irrespective
the condition specified
of the condition
The block code is The block of code is
controlled at the end controlled at starting

275

23
"switch" statement
 A switch statement can replace multiple if checks.

 The switch has one or more case blocks and an


optional default. It looks like this:

switch(x) {
case 'value1': // if (x === 'value1')
[break]
case 'value2': // if (x === 'value2')
default:
}
276

let a = 2 + 2;
switch (a)
{
case 3:
alert( 'Too small' );
break;
case 4:
alert( 'Exactly!' );
break;
case 5:
alert( 'Too big' );
break;
default:
alert( "I don't know such values" );
} 277

let a = 2 + 2;
switch (a) {
case 3:
alert( 'Too small' );
case 4:
alert( 'Exactly!' );
case 5:
alert( 'Too big' );
default:
alert( "I don't know such values" );
}

278

24
let a = "1";
let b = 0;

switch (+a) {
case b + 1:
alert("this runs, because +a is 1, exactly equals b+1");
break;

default:
alert("this doesn't run");
}

279

let a = 3;

switch (a) {
case 4:
alert('Right!');
break;

case 3: // (*) grouped two cases


case 5:
alert('Wrong!');
alert("Why don't you take a math class?");
break;

default:
alert('The result is strange. Really.');
}

280

let arg = prompt("Enter a value?");


switch (arg)
{ case '0’:
case '1':
alert( 'One or zero' );
break;
case '2':
alert( 'Two' );
break;
case 3:
alert( 'Never executes!' );
break;
default:
alert( 'An unknown value' );
} 281

25
Functions
 Functions are a collection of JavaScript statement that
performs a specified task.

 Functions are used whenever it is necessary to repeat


an operation.

 Functions are one of the fundamental building blocks in


JavaScript.

 A function in JavaScript is similar to a procedure—a set


of statements that performs a task or calculates a
value.

Functions

 Functions have inputs and outputs.

 The inputs are passed into the function and are known
as arguments or parameters.

 Think of a function as a “black box” which performs an


operation.

Defining Functions

 The most common way to define a function is with the


function statement.

 The function statement consists of the function keyword


followed by the name of the function, a comma-
separated list of parameter names in parentheses, and
the statements which contain the body of the function
enclosed in curly braces.

26
Example: Function

function square(x) Name of Function: square


{return x*x;}

Input/Argument: x
z = 3;
sqr_z = square(z); Output: x*x

Example: Function

function sum_of_squares(num1,num2)
{return (num1*num1) + (num2*num2);}

function sum_of_squares(num1,num2)
{return (square(num1) + square(num2));}

function sum(x, y) {
return x + y;
}
[Link](sum(6, 9));

// Function Definition
function welcomeMsg(name)
{
return ("Hello " + name + " welcome to
JavaScript Class");
}

let nameVal = “MCA-User";

// calling the function


[Link](welcomeMsg(nameVal));

287

27
Arrow Functions

 Arrow functions are a concise syntax for writing functions,


introduced in ES6, and they do not bind their own this
context.

 Syntax:

let function_name = (argument1, argument2 ,..) => expression

288

const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = [Link](function (s)


{
return [Link];
});

[Link]("Normal way ", a2);


const a3 = [Link]((s) => [Link]);
[Link]("Using Arrow Function ", a3);

Output

Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
289

Immediately Invoked Function


Expression (IIFE)

 IIFE functions are executed immediately after their


definition. They are often used to create isolated
scopes.

(function ()
{
[Link]("This runs immediately!");
}
) ();

290

28
Callback Functions

 A callback function is passed as an argument to another


function and is executed after the completion of that
function.

function num(n, callback) {


return callback(n);
}
const double = (n) => n * 2;
[Link](num(5, double));

291

Anonymous Functions
 Anonymous functions are functions without a name.
They are often used as arguments to other functions.

setTimeout(function () {
[Link]("Anonymous function executed!");
}, 1000);

292

Nested Functions
 Functions defined within other functions are called
nested functions. They have access to the variables of
their parent function.

function outerFun(a) {
function innerFun(b) {
return a + b;
}
return innerFun;
}
const addTen = outerFun(10);
[Link](addTen(5)); 293

29
Pure Functions
 Pure functions return the same output for the
same inputs and do not produce side effects. They
do not modify state outside their scope, such as
modifying global variables, changing the state of
objects passed as arguments, or performing I/O
operations.

function pureAdd(a, b)
{
return a + b;
}
[Link](pureAdd(2, 3));

294

<html> <head> </head>


<body style = "text-align: center; font-size: 20px;">
<h1> Welcome to the javaScript </h1>
Enter a number: <input id = "num"> <br><br>
<button onclick = "fact()"> Factorial </button>
<p id = "res"></p>
<script>
function fact(){
var i, num, f;
f = 1;
num = [Link]("num").value;
for(i = 1; i <= num; i++)
{ f = f * i; }
i = i - 1;
[Link]("res").innerHTML = "The factorial of th
e number " + i + " is: " + f ; 295

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

function fact(num)
{
if (num == 0) {
return 1;
}
else {
return num * fact( num - 1 );
}
}

296

30
function map(f, a) {
const result = new Array([Link]);
for (let i = 0; i < [Link]; i++) {
result[i] = f(a[i]);
}
return result;
}
const numbers = [0, 1, 2, 5, 10];
const cubedNumbers = map(function (x) {
return x * x * x;
}, numbers);
[Link](cubedNumbers);

297

let myFunc;
if (num === 0) {
myFunc = function (theObject)
{
[Link] = "Toyota";
};
}

const num1 = 20;


const num2 = 3;
const name = "Chamakh";

function multiply() {
return num1 * num2;
}
[Link](multiply());

298

function getScore() {
const num1 = 2;
const num2 = 3;

function add() {
return `${name} scored ${num1 + num2}`;
}

return add();
}

[Link](getScore());

299

31
function A(x) {
function B(y) {
function C(z) {
[Link](x + y + z);
}
C(3);
}
B(2);
}
A(1);

300

Key Characteristics of Functions


 Parameters and Arguments: Functions can accept
parameters (placeholders) and be called with arguments
(values).

 Return Values: Functions can return a value using the


return keyword.

 Default Parameters: Default values can be assigned to


function parameters.

301

Advantages of Functions in JavaScript

 Reusability: Write code once and use it multiple times.

 Modularity: Break complex problems into smaller,


manageable pieces.

 Improved Readability: Functions make code easier to


understand.

 Maintainability: Changes can be made in one place


without affecting the entire codebase.

302

32
What can a JavaScript Do?
 JavaScript gives HTML designers a programming
tool:
 simple syntax
 JavaScript can put dynamic text into an HTML
page
 JavaScript can react to events
 JavaScript can read and write HTML elements
 JavaScript can be used to validate data
 JavaScript can be used to detect the visitor’s
browser
 JavaScript can be used to create cookies
 Store and retrieve information on the visitor’s
computer
303

JavaScript How To
 The HTML <script> tag is used to insert a JavaScript into
an HTML page
<script type=“text/javascript”>
[Link](“Hello World!”)
</script>
 Ending statements with a semicolon?
 Optional; required when you want to put multiple
statements on a single line
 JavaScript can be inserted within the head, the body, or
use external JavaScript file
 How to handle older browsers?
<script type=“text/javascript”>
<!—
[Link](“Hello World!”)
// -->
</script>
304

Where to place JavaScript

 JavaScript can be placed in the <head> section of an HTML


page. (Embedded Js).

 JavaScript can be placed in the <body> section of an HTML


page. (Internal Js)

 JavaScript can also be placed in external files and then linked


to HTML Page. (External Js)

305

33
JavaScript in <head>

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("p1").innerHTML = "Paragraph replaced by me";
}
</script>
</head>
<body>
<p id="p1">Paragraph.</p>

<button type="button" onclick="myFunction()">Click me!!</button>

</body>
</html>

JavaScript in <body>

<!DOCTYPE html>
<html>
<body>
<p id="p1">Paragraph.</p>

<button type="button" onclick="myFunction()">Click me!!</button>


<script>
function myFunction() {
[Link]("p1").innerHTML =
"Paragraph replaced by me";
}
</script>
</body>
</html>

External JavaScript
 Scripts can also be placed in external files:
 External file: [Link]
function myFunction() {
[Link]("demo").innerHTML =
"Paragraph changed.";
}

 External scripts are practical when the same code is used


in many different web pages.
 JavaScript files have the file extension .js.
 To use an external script, put the name of the script file
in the src (source) attribute of a <script> tag:

34
 You can place an external script reference in <head> or <body> as you like.
 The script will behave as if it was located exactly where the <script> tag is
located.
External JavaScript Advantages
Placing scripts in external files has some advantages:
 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads

 You can also add several script files to one page - use several script tags:
<script src="[Link]"></script>
<script src="[Link]"></script>

Document Object Model (DOM)


 The DOM defines a standard for accessing
documents.

 It is a platform that allows programs and scripts


to dynamically access and update the content,
structure, and style of a document.

 The HTML DOM is a standard for how to get,


change, add, or delete HTML elements.

310

311

35
 HTML DOM methods are actions you can perform (on
HTML Elements).
 HTML DOM properties are values (of HTML Elements)
that you can set or change.

<html> <body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hell
o World!";
</script> </body> </html>

 In the example above, getElementById is a method,


while innerHTML is a property.

312

JavaScript HTML DOM Elements

 Finding HTML elements by id


 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections

313

Finding HTML Elements by Id


<html> <body>
<h2>JavaScript HTML DOM</h2>
<p id="intro">Finding HTML Elements by Id</p>
<p>This example demonstrates the
<b>getElementsById</b> method.</p>
<p id="demo"></p>
<script>
const element = [Link]("intro");
[Link]("demo").innerHTML =
"The text from the intro paragraph is: " +
[Link];
</script>
</body>
</html> 314

36
<html> <body>
<h2>JavaScript HTML DOM</h2>
<div id="main">
<p>Finding HTML Elements by Tag Name</p>
<p>This example demonstrates the
<b>getElementsByTagName</b> method.</p>
</div>
<p id="demo"></p>
<script>
const x = [Link]("main");
const y = [Link]("p");
[Link]("demo").innerHTML =
'The first paragraph (index 0) inside "main" is: ' +
y[0].innerHTML;
</script></body></html>
315

Finding HTML Elements by Class Name

<html> <body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Class Name.</p>
<p class="intro">Hello World!</p>
<p class="intro">This example demonstrates the
<b>getElementsByClassName</b> method.</p>
<p id="demo"></p>
<script>
const x = [Link]("intro");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' +
x[0].innerHTML;
</script> </body> </html>
316

Finding HTML Elements by Query Selector


<html> <body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Query Selector</p>
<p class="intro">Hello World!.</p>
<p class="intro">This example demonstrates the
<b>querySelectorAll</b> method.</p>
<p id="demo"></p>
<script>
const x = [Link]("[Link]");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' +
x[0].innerHTML;
</script></body></html>
317

37
Finding HTML Elements by HTML Object
Collections

<html> <body> <p>These are the values of each


<h2>JavaScript HTML DOM</h2> element in the form:</p>
<p id="demo"></p>
<p>Finding HTML Elements Using
<script>
<b>[Link]</b>.</p>
const x = [Link]["frm1"];
<form id="frm1" let text = "";
action="/action_page.php"> for (let i = 0; i < [Link] ;i++) {
First name: <input type="text" text += [Link][i].value + "<br>";
name="fname" value="Donald"><br> }
[Link]("demo").in
Last name: <input type="text" nerHTML = text;
name="lname" value="Duck"><br><br>
</script>
<input type="submit" </body>
value="Submit"> </html>
</form>
318

 The following HTML objects (and object collections) are


also accessible:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]

319

Changing HTML

 The easiest way to modify the content of an HTML


element is by using the innerHTML property.

 To change the content of an HTML element, use this


syntax:

[Link](id).innerHTML = new HTML

320

38
<html>
<body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p>
<script>
[Link]("p1").innerHTML = "New text!";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>

This example changes the content of a <P> :

321

Changing the Value of an Attribute

 To change the value of an HTML attribute, use this


syntax:

[Link](id).attribute = new value

<html>
<body>

<img id="myImage" src="[Link]">

<script>
[Link]("myImage").src =
"[Link]";
</script>

</body>
</html>
322

Dynamic HTML content

 JavaScript can create dynamic HTML content:

<html>
<body>
<script>
[Link]("demo").innerHTML = "Date :
" + Date(); </script>
</body>
</html>

323

39
[Link]()
 In JavaScript, [Link]() can be used to write
directly to the HTML output stream:

<html>
<body>
<p>Bla bla bla</p>
<script>
[Link](Date());
</script>
<p>Bla bla bla</p>
</body>
</html>
Never use [Link]() after the
document is loaded. It will overwrite the
document. 324

<html><head><script>
function validateForm() {
let x = [Link]["myForm"]["fname"].value;
if (x == "") {alert("Name must be filled out");
return false;
}}
</script></head>
<body>
<h2>Form Validation</h2>
<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form></body></html> 325

JavaScript HTML DOM Events

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

326

40
 <!DOCTYPE html>
<html>
<body>

<h1 onclick="changeText(this)">Click on this


text!</h1>

<script>
function changeText(id) {
[Link] = "Ooops!";
}
</script>

</body>
</html>

327

Convert Fahrenheit to Celsius:

41

You might also like