SlideShare a Scribd company logo
Mr. K. Chairmadurai,
Assistant Professor/ CSE
Adhiparasakthi Engineering College,
Melmaruvathur.
Syllabus :
Java Script JSON
-An introduction to JavaScript
-JavaScript DOM Model
-Date and Objects,
-Regular Expressions
-Exception Handling
-Validation
-Built-in objects
-Event Handling
- DHTML with JavaScript
-Introduction
– Syntax
– Function Files
– Http Request
–SQL
Introduction to JavaScript
• JavaScript is one of the 3 languages all web
developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout & design of web pages
3. JavaScript to program the behavior of web pages
• JavaScript is a case-sensitive language.
Introduction to JavaScript
• JavaScript is a client-side, object-based scripting
language that is used to handle and validate client-side data.
JavaScript is also used for making the user interface of the
web pages more dynamic.
• JavaScript is a lightweight scripting language based on ECMA
Script standards. It executes on the browser and therefore
reduces the load on the server.
• It is an interpreted language which means the script written
inside Javascript is processed line by line and is not compiled
before processing. These Scripts are interpreted by JavaScript
interpreter which is a built-in component of the Web
browser.
• JavaScript is Platform Independent, which means you need to
write the script once and can run it on any platform or
browser without affecting the output of the Script.
Introduction to JavaScript
• Browsers use their own JavaScript Engines to
execute the JavaScript code.
• Some commonly used browsers are listed
below:
– Chrome uses a V8 engine.
– Firefox uses the SpiderMonkey engine.
– Microsoft Edge uses the ChakraCore engine.
– Safari uses the SquirrelFish engine.
JavaScript Features
• Light Weight
– JavaScript is a lightweight scripting language because it is made for data handling
at the browser level only.
• Dynamically Typed
– JavaScript supports dynamic typing which means types of the variable are
defined based on the stored value.
• Object-Based
– JavaScipt is an object-based scripting language that provides built-in objects like
String, Math, Date, etc.
• Functional
– This implies that JavaScript uses a functional approach, even objects are created
from the constructor functions and each constructor function represents a
unique object-type.
• Platform Independent
– you can write your JavaScript applications and run them on any platform or any
browser without affecting the output of the Script.
• Prototype-based
– In JavaScript, each constructor function is associated with a prototype object.
JavaScript Features
• Interpreted
– JavaScript is an interpreted language which means the script written inside javascript
is processed line by line. These scripts are interpreted by JavaScript interpreter which
is a built-in component of the Web browser.
• Asynchronous
– JavaScript can be used to do complex processing asynchronously which means that
the whole page will not have to wait for the JavaScript processing, and once the
script processing completes we can easily modify the HTML code to show or hide
data.
• Client-side Validations
– This is a feature which is available in JavaScript since forever and is still widely used
because every website has a form in which users enter values, and to make sure that
users enter the correct value, we must put proper validations in place, both on the
client-side and on the server-side. JavaScript is used for implementing client-side
validations.
• More control in Browser
– JavaScript being a client-side language provides many features that help developers to
divide processing between browser and server hence reducing the load on servers by
having basic processing, validations, temporary data saving using cookies, etc on the
Advantages of JavaScript
• JavaScript makes the webpage more interactive and dynamic.
• By using JavaScript you can make your webpage to give
immediate feedback to the user so that they would not have to
reload the page.
• You can use JavaScript to perform actions based on how the
user interacts with your webpage using the events generated
like a mouse click, form submit, button click and a lot more.
• JavaScript can save server traffic by validating the user
inputs before even sending data to the server.
• JavaScript can be used to store client-side cookies to store data
on the client-side and then read them or delete them.
• JavaScript can be used to make async HTTP calls to load data
from the server.
Applications of JavaScript
• Client-side validation,
• Manipulating HTML Pages
• Dynamic drop-down menus,
• Displaying date and time,
• User Notifications
• Displaying pop-up windows and dialog boxes
(like an alert dialog box, confirm dialog box
and prompt dialog box),
• Displaying clocks etc.
JavaScript Output
• JavaScript can "display" data in different ways:
• Writing into the HTML output
using document.write().
• Writing into an HTML element,
using innerHTML.
• Writing into an alert box, using window.alert().
• Writing into the browser console,
using console.log().
Using innerHTML
• To access an HTML element, JavaScript can use
the document.getElementById(id) method.
• The id attribute defines the HTML element.
The innerHTML property defines the HTML content:
Using document.write()
• JavaScript lets you write any output
into the HTML webpage by using
the document.write() method.
• By using this method you can
directly write output to the HTML
page.
• Using document.write() after an
HTML document is loaded,
will delete all existing HTML
• The document.write() method
should only be used for testing.
Using window.alert()
• There are certain websites that give you
alert messages when you access them
or when you perform some action you
see the output message in alert boxes.
• You can also make your webpage to send
alert messages to notify something to
the user using JavaScript, to use this
feature you need to use
the window.alert() method.
What JavaScript can do
• JavaScript Can Change HTML Content
– document.getElementById("demo").innerHTML = "Hello JavaScript";
• JavaScript Can Change HTML Attribute Values
– document.getElementById('myImage').src='pic_bulbon.gif'
• JavaScript Can Change HTML Styles (CSS)
– document.getElementById("demo").style.fontSize = "35px";
• JavaScript Can Hide HTML Elements
– document.getElementById("demo").style.display = "none";
JavaScript Where To Write
<Script> tag
• In HTML, JavaScript code is inserted
between <script> and </script> tags.
<script ...>
JavaScript code
</script>
• Scripts can be placed in the <body>, or
in the <head> section of an HTML page,
or in both
< Script> Attributes
• Src - It specifies the uniform source locator(URL)
of a file that contains the script.
• Type − This attribute is what is now recommended
to indicate the scripting language in use and its
value should be set to "text/javascript".
Include JavaScript in an HTML file
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head>
sections.
• Script in an external file and then include in
<head>...</head> section.
<html>
<head>
<script>
document.write("Hai World!")
</script>
<head>
<body>
<p> Welcome to Java Script </p>
</body>
</html>
JavaScript in <head>...</head> section
<html>
<body>
<script>
document.write("Hello World!")
</script>
</body>
</html>
JavaScript in <body>...</body> section
<html>
<head>
<script>
document.write("I am in Head Tag")
</script>
</head>
<body>
<br>
<script> document.write("I am in Body Tag") </script>
</body>
</html>
JavaScript in <head> and<body> section
document.write("I am printing
from External script file")
JavaScript in External File
<html>
<head>
<script src = "external.js" >
</script>
</head>
<body> </body>
</html>
sample.html external.js
Advantages of External JavaScript File
• It separates the HTML and JavaScript code and
makes the code look clean and easy to
understand also maintain.
• External JavaScript code can be reused in multiple
HTML webpages.
• External JavaScript code can be cached in the
browser.
• Once cached the browser will not load the
JavaScript file again and again and will use the
cached version of it. This will make your webpage
loading fast.
Basic JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript
programs are constructed:
Basic JavaScript Syntax
Notice that there is no main() function/method
Basic JavaScript Syntax
Comments like Java/C++ (/* */ also allowed)
• Comments refer to the text or code in a program that is ignored at the
time of executing the program.
• Comments are used to provide additional information in the code, such as
the description of code.
• And it is considered as good practice to add comments to your code.
Single line comments start with //. Multi-line comments
start with /* and end with */.
Basic JavaScript Syntax
Variable declarations:
- Not required
- Data type not specified
• In a programming language, variables are used to store data
values.
• JavaScript uses the
keywords var, let and const to declare variables.
• An equal sign is used to assign values to variables.
Basic JavaScript Syntax
Semi-colons are usually
not required, but always
allowed at statement end
• Semicolons separate JavaScript statements.
• Add a semicolon at the end of each executable
statement
Basic JavaScript Syntax
Arithmetic operators same as Java/C++
JavaScript uses arithmetic operators ( + - * / ) to compute values:
JavaScript uses an assignment operator ( = ) to assign values to variables:
An expression is a combination of values, variables, and operators,
which computes to a value.
Basic JavaScript Syntax
String concatenation operator
as well as addition
Basic JavaScript Syntax
Arguments can be any expressions
Argument lists are comma-separated
Basic JavaScript Syntax
Object dot notation for method calls as in Java/C++
Basic JavaScript Syntax
Many control constructs and use of
{ } identical to Java/C++
Basic JavaScript Syntax
Most relational operators syntactically
same as Java/C++
Basic JavaScript Syntax
Automatic type conversion:
guess is String,
thinkingOf is Number
JavaScript Variables
• Variables are containers for storing data
(storing data values).
• 4 Ways to Declare a JavaScript Variable:
– Using var
– Using let
– Using const
– Using nothing
JavaScript Variables
var x = 5;
var y = 6;
var z = x + y;
let x = 5;
let y = 6;
let z = x + y;
x = 5;
y = 6;
z = x + y;
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
JavaScript Data Types
• JavaScript Data types are used to identify the type of data that
is stored inside a variable during the script execution.
• As we have already specified about the Dynamic
Typed JavaScript feature so we do not have to specify the data
type of the variable while declaring it.
• JavaScript broadly supports three types of Data types, they are:
• Primitive Type
• Reference Type
• Special Data Type
JavaScript Primitive Data Type
• JavaScript Primitive data types can be classified further into the following
types:
– String Data Type
– Boolean Data Type
– Number Data Type
JavaScript Composite(Reference) Data types
• These data types can hold collections of values and more complex entities.
• It is further divided into Object, Array and Function.
– Object data type Array data type Function data type
• In JavaScript, an object data type is used to store the collection of data.
Object's properties are written as key:value pairs, which are separated by
commas and enclosed within curly braces {}.
• The key (name) must always be a string, but the value can be of any data
type.
• JavaScript Array data type is written inside a pair of square brackets [] and is
used to store multiple values of the same datatype be it strings, numbers
etc.
var welcome = function() {
return "Welcome!";
}
JavaScript Special Data types
• Undefined Data type
– When a variable is just declared and is not assigned any value, it has undefined as its value.
– Yes, undefined is a valid data type in JavaScript and it can have only one value which
is undefined.
• Null Data type
– JavaScript Null data type is used to represent no value. It is not similar to undefined, and
neither it is similar to empty value or zero value.
– The Null datatype means, the variable has been defined but it contains no value.
– The Null data type can have only one value, which is null.
Variables and Data Types
• The typeof operator in JavaScript can be used
to check the data type of any variable.
• typeof operator returns string related to
data type
– Syntax: typeof expression
• Example:
Variables and Data Types
JavaScript Operators
• An operator is a symbol that is reserved for special tasks or operations.
• Operators are used to performing operations on the operands.
• The operands can be variables or numeric literals or string literals.
• An operator can work on one or more than one operand.
• JavaScript supports a rich set of operators.
• These operators perform a specific task and every operator has different
properties.
• The list of operators is given below:
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• String Operators
JavaScript Arithmetic Operators
JavaScript Assignment Operators
JavaScript String Operators
JavaScript Comparison Operators
JavaScript Logical Operators
JavaScript Type Operators
JavaScript Bitwise Operators
Operators
Example
Operators
Example
JavaScript Functions
• JavaScript function is a set of statements that are used to perform a specific task.
• It can take one or more input and can return output as well.
• A JavaScript function is a block of code designed to perform a particular task.
• A JavaScript function is executed when "something" invokes it (calls it).
Structure of a JavaScript function
JavaScript function - Example
<script type = "text/javascript">
function welcomeMsg(name) // Function definition
{
document.write("Hello " + name + " welcome to javascript");
}
var nameVal= “CSE"; // creating a variable
welcomeMsg(nameVal); // calling the function
</script>
JavaScript function - Example
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
JavaScript Objects
• In JavaScript, we can define an object as a collection of properties
that are defined as a key-value pair, where the key is the generic
name of the object feature which can be assigned a value.
• In JavaScript, an object is a standalone entity where the properties of
the object define the characteristics of the object.
– For example, if we consider a mobile phone as an object then its
properties are its color, screen size, brand name, operating system,
RAM, Memory, etc. All these properties define the characteristics of a
mobile phone.
• The property of an object is a key:value pair, where key refers to a
variable, and value refers to any type of value associated with the key.
The value can be of any type like a number, string, or even an array, or
another object.
Creating Objects in JavaScript
• We can create an object in JavaScript either by
using
– the constructor function or
– the object literal.
Creating Objects in JavaScript
JavaScript Object Using Object Literal Syntax
JavaScript Object Using Object Constructor
Accessing Object Properties
• objectName.propertyName
• objectName["propertyName"]
Add new Property to JavaScript Object
Remove and update Property of a
JavaScript Object
Traversing(Enumerating) JavaScript
Object
Accessing Object Properties from
object literals
Accessing Object Properties from
object constructor
Add new Property to JavaScript Object
By using an Object constructor
using this keyword
• Here, you need to create function with
arguments.
• Each argument value can be assigned in the
current object by using this keyword.
• The this keyword refers to the current object.
• Here this keyword is used to refer to the object
that has been passed to a function
By using an Object constructor
using this keyword
By using an Object constructor
using this keyword
By using an Object constructor
using this keyword
Creating Method in JavaScript Object
• A method is a function associated with an object.
• Methods are defined just as normal JavaScript
functions are defined, except that they have to be
assigned to an object as a property.
• But before defining method, we need to add
property in the function with same name as
method.
Method in JavaScript
Object
Method in JavaScript
Object
JavaScript Built-in Objects
• JavaScript has rich set of built-in objects that can
be used to deal with various types of collections.
• Some commonly used built-in types are listed
below.
• String
• RegExp
• Boolean
• Number
• Array
• Math
• Date
JavaScript Boolean Object
• JavaScript Boolean is an object that represents value in two
states: true or false.
• It is used to create a Boolean object which holds true or false value,
depending upon the value used while creating the Boolean object.
• The Boolean object's true and false values are different from the primitive
boolean type's true and false values.
– The Boolean object returns false when it is passed with values such as 0, -0, an
empty string(""), false, null, undefined, or Not a Number(NaN) while creating
the Boolean object.
– Apart from all these values which set the initial value as false for the Boolean
object, all other values, even an empty array([]), empty object({}) or the string
"false", will set the initial value for the Boolean object as true.
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
Creating JavaScript Boolean Object
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
Methods of Boolean Object
• The following are some of the commonly used methods of
the Boolean object.
– toString(): converts the boolean value into a string and returns
the string.
– valueOf(): returns the primitive value of a Boolean object.
JavaScript Number Object
• JavaScript Number is a built-in wrapper object which is
used to work with numerical values.
• A Number object can be created using
the Number() constructor.
• All numbers are 64 bit(8 bytes) floating-point numbers.
Unlike C or C++, there are no data types
like integer, float, etc, to define numbers in JavaScript
Creating JavaScript Number Object
290.78
object
JavaScript Number Object Properties
JavaScript Number Object Properties
JavaScript Number Object Methods
JavaScript Number Object Methods
JavaScript Math Object
• In JavaScript, Math is a built-in object which includes properties and
methods for mathematical operations.
• We can use the Math object to perform simple and complex
arithmetic operations.
• Note: Math works with the JavaScript Number type only.
• In Math object, All the properties and methods are static. So, we don't
need to create its object to use its property or method. Also, even if we
want, we cannot create an object as Math is not a
constructor function.
JavaScript Math Properties
JavaScript
Math Properties
JavaScript Math Methods
JavaScript Math Methods
JavaScript Math Methods
JavaScript Date Object
• JavaScript Date object is a built-in object which is used to deal with date
and time.
• It stores a Number which represents milliseconds for the Unix
Timestamp(which is nothing but milliseconds passed since 1 January 1970
UTC).
• We can use it to create a new date, format a date, get elapsed time
between two different time values, etc.
• It also helps to get a date value using milliseconds number and we can get a
date based on the different timezones as well.
• The Date object use browser's date timezone by default and display date in
the text format.
• The Date object can be created using the Date constructor function.
Creating the JavaScript Date Object
• new Date( )
• new Date(milliseconds)
• new Date(datestring)
• New Date(year,month,date[,hour,minute,second,millisecond ])
• create a new Date object with the current date and time stored in it.
• string formats to create a date object.
• Date() constructor can take 7 arguments to create a date, which is: year, month, day, hour, minute, second,
and millisecond.
• get a date by just passing milliseconds
Tue May 05 2020 21:16:17 GMT+0530 (India Standard Time)
Wed Feb 13 1991 06:44:00 GMT+0530 (India
Standard Time)
Wed Feb 13 1991 06:44:00 GMT+0530 (India
Standard Time)
Tue Dec 25 2018 12:25:12 GMT+0530 (India Standard Time)
Fri Nov 05 2027 01:03:20 GMT+0530 (India Standard Time)
JavaScript Date Object Methods
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
JavaScript Date
Object Methods
JavaScript Regular Expression (Regex)
• In JavaScript, a Regular Expression (RegEx) is an object that describes a
sequence of characters used for defining a search pattern.
/^a...s$/
The above code defines a RegEx pattern.
The pattern is: any five letter string starting with a and ending with s.
A pattern defined using RegEx can be used to match against a string.
Expression String Matched?
/^a...s$/
abs No match
alias Match
abyss Match
Alias No match
An abacus No match
Creating a regular expression
• There are two ways you can create a regular expression in
JavaScript.
• Using a regular expression literal:
The regular expression consists of a pattern enclosed
between slashes.
• Using the RegExp() constructor function:
You can also create a regular expression by calling
the RegExp() constructor function.
Specify Pattern Using RegEx - Quantifiers
• In the above example (/^a...s$/), ^ and $ are
quantifiers.
• When we want to concatenate a regular
expression with itself multiple times, we can
use the quantifier shorthand notation
[] . ^ $ * + ? {} ()  |
[] Square brackets
• Square brackets specify a set of characters you
wish to match.
• Here, [abc] will match if the string you are
trying to match contains any of the a, b or c.
Expression String Matched?
[abc]
a 1 match
ac 2 matches
Hey Jude No match
abc de ca 5 matches
[] Square brackets
• You can also specify a range of characters
using - inside square brackets.
– [a-e] is the same as [abcde].
– [1-4] is the same as [1234].
– [0-39] is the same as [01239].
• You can complement (invert) the character
set by using caret ^ symbol at the start of a
square-bracket.
– [^abc] means any character except a or b or c.
– [^0-9] means any non-digit character.
. Period
• A period matches any single character (except
newline 'n').
Expression String Matched?
..
a No match
ac 1 match
acd 1 match
acde
2 matches
(contains 4
characters)
^ Caret
• The caret symbol ^ is used to check if a
string starts with a certain character.
Expression String Matched?
^a
a 1 match
abc 1 match
bac No match
^ab
abc 1 match
acb
No match (starts
with a but not
followed by b)
$ Dollar
• The dollar symbol $ is used to check if a
string ends with a certain character.
Expression String Matched?
a$
a 1 match
formula 1 match
cab No match
* Star
• The star symbol * matches zero or more
occurrences of the pattern left to it.
Expression String Matched?
ma*n
mn 1 match
man 1 match
mann 1 match
main
No match (a is
not followed by
n)
woman 1 match
+ Plus
• The plus symbol + matches one or more
occurrences of the pattern left to it.
Expression String Matched?
ma+n
mn
No match (no a
character)
man 1 match
mann 1 match
main
No match (a is not
followed by n)
woman 1 match
? Question Mark
• The question mark symbol ? matches zero or
one occurrence of the pattern left to it.
Expression String Matched?
ma?n
mn 1 match
man 1 match
maan
No match (more than
one a character)
main
No match (a is not
followed by n)
woman 1 match
{} Braces
• Consider this code: {n,m}. This means at
least n, and at most m repetitions of the
pattern left to it.
Expression String Matched?
a{2,3}
abc dat No match
abc daat 1 match (at daat)
aabc daaat
2 matches (at aabc
and daaat)
aabc daaaat
2 matches (at aabc
and daaaat)
| Alternation
• Vertical bar | is used for alternation
(or operator).
Expression String Matched?
a|b
cde No match
ade
1 match
(match at
ade)
acdbea
3 matches (at
acdbea)
() Group
• Parentheses () is used to group sub-patterns.
For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz
Expression String Matched?
(a|b|c)xz
ab xz No match
abxz
1 match (match
at abxz)
axz cabxz
2 matches (at
axzbc cabxz)
Quantifiers
Special Sequences - Meta Characters
• Special sequences make commonly used patterns
easier to write.
• Meta characters are characters that are interpreted
in a special way by a RegEx engine.
• A - Matches if the specified characters are at the
start of a string.
Expression String Matched?
Athe
the sun Match
In the sun No match
b
• b - Matches if the specified characters are at
the beginning or end of a word.
Expression String Matched?
bfoo
football Match
a football Match
foob
a football No match
the foo Match
the afoo test Match
the afootest No match
B
• B - Opposite of b. Matches if the specified
characters are not at the beginning or end of
a word.
Expression String Matched?
Bfoo
football No match
a football No match
fooB
a football Match
the foo No match
the afoo test No match
the afootest Match
d
• d - Matches any decimal digit. Equivalent
to [0-9]
Expression String Matched?
d
12abc3
3 matches
(at 12abc3)
JavaScript No match
D
• D - Matches any non-decimal digit.
Equivalent to [^0-9]
Expression String Matched?
D
1ab34"50
3 matches (at
1ab34"50)
1345 No match
s
• s - Matches where a string contains any
whitespace character.
Expression String Matched?
s
JavaScript RegEx 1 match
JavaScriptRegEx No match
S
• S - Matches where a string contains any non-
whitespace character.
Expression String Matched?
S
a b
2 matches
(at a b)
w
• w - Matches any alphanumeric character
(digits and alphabets).
• Equivalent to [a-zA-Z0-9_].
• By the way, underscore _ is also considered an
alphanumeric character.
Expression String Matched?
w
12&": ;c
3 matches (at
12&": ;c)
%"> ! No match
W
• W - Matches any non-alphanumeric
character. Equivalent to [^a-zA-Z0-9_]
Expression String Matched?
W
1a2%c
1 match
(at 1a2%c)
JavaScript No match
Z
• Z - Matches if the specified characters are at
the end of a string
Expression String Matched?
JavaScriptZ
I like JavaScript 1 match
I like JavaScript
Programming
No match
JavaScript is fun No match
Regular Expression Flags Modifier
• Flags are used with regular expressions that
allow various options such as global search,
case-insensitive search, etc.
• They can be used separately or together.
JavaScript Regular Expression Methods
• In JavaScript, you can use regular expressions
with RegExp() methods:
– test() and exec().
• There are also some string methods that allow
you to pass RegEx as its parameter.
• They are:
– match(), replace(), search(), and split().
JavaScript Regular Expression
Methods
Method Description
exec()
Executes a search for a match in a string and returns an array of
information. It returns null on a mismatch.
test() Tests for a match in a string and returns true or false.
match()
Returns an array containing all the matches. It returns null on a
mismatch.
matchAll() Returns an iterator containing all of the matches.
search()
Tests for a match in a string and returns the index of the match.
It returns -1 if the search fails.
replace()
Searches for a match in a string and replaces the matched
substring with a replacement substring.
split() Break a string into an array of substrings.
JavaScript Regular Expression Methods
Regular Expression Modifier
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
JavaScript Exception Handling
• An Exception is an error that occurs at the time
of execution(runtime) due to an illegal
operation when a program is syntactically
correct.
– For example, whenever you try to reference an
undefined variable or call a non-existent method;
an exception will occur.
• The try, catch and finally blocks are used to
handle exceptions (a type of an error).
Types of Errors
• While coding, there can be three types of errors in the
code:
• Syntax Error: When a user makes a mistake in the pre-
defined syntax of a programming language, a syntax
error may appear.
• Runtime Error: When an error occurs during the
execution of the program, such an error is known as
Runtime error. The codes which create runtime errors
are known as Exceptions. Thus, exception handlers are
used for handling runtime errors.
• Logical Error: An error which occurs when there is any
logical mistake in the program that may not produce the
desired output, and may terminate abnormally. Such an
error is known as Logical error.
Throw, and Try...Catch...Finally
• The try statement defines
– a code block to run (to try).
• The catch statement defines
– a code block to handle any error.
• The finally statement defines
– a code block to run regardless of the result.
• The throw statement defines
– a custom error.
JavaScript try and catch
• The try statement allows you to define a block of
code to be tested for errors while it is being
executed.
• The catch statement allows you to define a block
of code to be executed, if an error occurs in the
try block.
• The JavaScript statements try and catch come in
pairs:
JavaScript try...catch...finally
Statement
• You can also use the try...catch...finally statement
to handle exceptions.
• The finally block executes both when the code
runs successfully or if an error occurs.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of
the try / catch result
}
JavaScript throw Statement
• In JavaScript, the throw statement handles user-
defined exceptions.
• We can use the throw statement in our JavaScript code
to throw a custom error/exception where we can
provide a message while throwing the error.
• This message can be a string message, a number or any
boolean type(true or false).
• throw expression;
– Here, expression specifies the value of the exception.
• The expression can be string, boolean, number, or
object value.
•
The Error Object
• JavaScript has a built in error object that
provides error information when an error
occurs.
• The error object provides two useful
properties: name and message.
Error Name Values
Range Error
Range Error
Type Error
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
Document Object Model in JavaScript
• JavaScript can access all the elements in a webpage making use of Document
Object Model (DOM).
• In fact, the web browser creates a DOM of the webpage when the web page is
loaded.
• The Document Object Model (DOM) is an application programming interface (API)
for manipulating HTML documents.
• The DOM represents an HTML document as a tree of nodes.
• The DOM provides functions that allow you to add, remove, and modify parts of
the document effectively.
• Note that the DOM is cross-platform and language-independent ways of
manipulating HTML and XML documents.
• The HTML DOM model is constructed as a tree of Objects
DOM Tree
DOM Tree
Document Object Model in JavaScript
• 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
What is the DOM?
• The DOM is a W3C (World Wide Web Consortium)
standard.
• The DOM defines a standard for accessing documents:
• "The W3C Document Object Model (DOM) is a
platform and language-neutral interface that allows
programs and scripts to dynamically access and
update the content, structure, and style of a
document."
• The W3C DOM standard is separated into 3 different
parts:
– Core DOM - standard model for all document types
– XML DOM - standard model for XML documents
– HTML DOM - standard model for HTML documents
What is the HTML DOM?
• The HTML DOM is a standard object model
and programming interface for HTML.
• It defines:
– The HTML elements as objects
– The properties of all HTML elements
– The methods to access all HTML elements
– The events for all HTML elements
• The HTML DOM is a standard for how to get, change,
add, or delete HTML elements.
A document as a hierarchy of nodes
• The DOM represents an HTML
document as a hierarchy of nodes.
• Consider the following HTML
document:
DOM Nodes
• With the HTML DOM, you can navigate the node tree
using node relationships.
• According to the W3C HTML DOM standard, everything in
an HTML document is a node:
– The entire document is a document node
– Every HTML element is an element node
– The text inside HTML elements are text nodes
– Every HTML attribute is an attribute node
– All comments are comment nodes
• With the HTML DOM, all
nodes in the node tree can
be accessed by JavaScript.
• New nodes can be created,
and all nodes can be
modified or deleted.
Relationships between nodes
• An HTML document can be
represented as a tree of nodes, like a
traditional family tree.
• Each markup can be represented as a
node with a specific node type.
• The node is the generic type of
element.
• Element is a specific type of node with
the node type Node.ELEMENT_NODE.
• In the DOM tree, a node has
relationships with other nodes.
Relationships between nodes
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
•<html> is the root node
•<html> has no parents
•<html> is the parent of <head> and <body>
•<head> is the first child of <html>
•<body> is the last child of <html>
•<head> has one child: <title>
•<title> has one child (a text node): "DOM
Tutorial"
•<body> has two children: <h1> and <p>
•<h1> has one child: "DOM Lesson one"
•<p> has one child: "Hello world!"
•<h1> and <p> are siblings
Navigating Between Nodes
• You can use the following node properties to navigate
between nodes with JavaScript:
– parentNode - childNodes[nodenumber]
– firstChild - lastChild
– nextSibling - previousSibling
– InnerHTML - to retrieve the content of an HTML element.
– document.body - The body of the document
– document.documentElement - The full document
– nodeName property specifies the name of a node.
– nodeName is read-only
– nodeName of an element node is the same as the tag name
– nodeName of an attribute node is the attribute name
– nodeName of a text node is always #text
– nodeName of the document node is always #documen
– nodeValue property specifies the value of a node.
– nodeValue for element nodes is null
– nodeValue for text nodes is the text itself
– nodeValue for attribute nodes is the attribute value
– nodeType property is read only. It returns the type of a
node.
InnerHTML
firstChild & nodeValue
childNodes[nodenumber]
document.body
document.documentElement
nodeName
nodeType
The HTML DOM Document Object
• 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.
– Finding HTML Elements
– Changing HTML Elements
– Adding and Deleting Elements
Finding HTML Elements
JavaScript getElementById
• The document.getElementById() method returns an Element object that
represents an HTML element with an id that matches a specified string.
• If the document has no element with the specified id,
the document.getElementById() returns null.
• Because the id of an element is unique within an HTML document,
the document.getElementById() is a quick way to access an element.
• If the HTML document has multiple elements with the same id,
the document.getElementById() method returns the first element it
encounters.
JavaScript getElementById
JavaScript getElementById
JavaScript getElementsByTagName
• The getElementsByTagName() is a method of the document object or a specific
DOM element.
• The getElementsByTagName() method accepts a tag name and returns a
live HTMLCollection of elements with the matching tag name in the order which
they appear in the document.
• The return collection of the getElementsByTagName() is live, meaning that it is
automatically updated when elements with the matching tag name are added
and/or removed from the document.
• Note that the HTMLCollection is an array-like object, like arguments object of a
function.
JavaScript getElementsByTagName
JavaScript getElementsByClassName
• The getElementsByClassName() method returns
an array-like of objects of the child elements
with a specified class name.
• The getElementsByClassName() method is
available on the document element or any other
elements.
JavaScript getElementsByClassName
JavaScript querySelector
• If you want to find all HTML elements that match a specified CSS selector (id, class
names, types, attributes, values of attributes, etc), use the querySelectorAll() method.
• The querySelector() finds the first element that matches a CSS selector or a group of
CSS selectors.
• The querySelectorAll() finds all elements that match a CSS selector or a group of CSS
selectors.
• A CSS selector defines elements to which a CSS rule applies.
JavaScript querySelector
JavaScript querySelector
JavaScript querySelector
JavaScript querySelector
Changing HTML Elements
• The HTML DOM allows JavaScript to change the
content of HTML elements.
• The easiest way to modify the content of an HTML
element is by using the innerHTML property.
Changing HTML Content
innerHTML property
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
Changing HTML Content
innerHTML property
<!DOCTYPE html>
<html>
<body>
<h1 id="id01">Old Heading</h1>
<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
</body>
</html>
Changing the Value of an Attribute
document.getElementById(id).attribute = new value
Changing HTML Style
document.getElementById(id).style.property = new style
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
Adding and Deleting Elements
Property/Method Description
createElement() Create a new element node
createTextNode() Create a new text node
node.textContent
Get or set the text content of an element
node
node.innerHTML
Get or set the HTML content of an
element
Adding and Deleting Elements
Property/Method Description
node.appendChild()
Add a node as the last child of a parent
element
node.insertBefore()
Insert a node into the parent element
before a specified sibling node
node.replaceChild() Replace an existing node with a new node
Inserting Nodes into the DOM
Method Description
node.removeChild() Remove child node
node.remove() Remove node
Removing Nodes from the DOM
Creating New HTML Elements (Nodes)
• To add a new element to the HTML
DOM, you must create the element
(element node) first, and then
append it to an existing element.
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
Removing Existing HTML Elements
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
Replacing HTML Elements
To replace an element to the HTML DOM, use the replaceChild() method:
JavaScript Events
• The change in the state of an object is known as an Event.
• In html, there are various events which represents that some activity
is performed by the user or by the browser.
• When JavaScript code is included in HTML, JavaScript react over these
events and allow the execution. This process of reacting over the
events is called Event Handling.
• Thus, JavaScript handles the HTML events via Event Handlers.
– For example, when a user clicks over the browser, add js code, which
will execute the task to be performed on the event.
JavaScript Events
Mouse events:
JavaScript Events
Form events:
Keyboard events:
JavaScript Events
Window/Document events
Click Event
Mouse Over
Focus
Keydown
Load
JavaScript Event Handlers
• Event handlers can be used to handle and verify user input,
user actions, and browser actions:
– Things that should be done every time a page loads
– Things that should be done when the page is closed
– Action that should be performed when a user clicks a button
– Content that should be verified when a user inputs data
• Many different methods can be used to let JavaScript work
with events:
– HTML event attributes can execute JavaScript code directly
– HTML event attributes can call JavaScript functions
– You can assign your own event handler functions to HTML
elements
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
JavaScript addEventListener()
• The addEventListener() method is used to attach an event handler to a
particular 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.
addEventListener() - Syntax
• The first parameter is the type of the 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.
element.addEventListener(event, function, useCapture);
Add an Event Handler to an Element
Add an Event Handler to an Element
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:
Add Many Event Handlers to the Same Element
Add Many Event Handlers to the Same Element
Event Bubbling or Event Capturing
• There are two ways of event propagation in the HTML DOM,
– bubbling and capturing.
• Event propagation is a way of defining the element order when an event occurs.
• If you have a <p> element inside a <div> element, and the user clicks on the <p>
element, which element's "click" event should be handled first?
– In bubbling the inner most element's event is handled first and then the outer: the
<p> element's click event is handled first, then the <div> element's click event.
– In capturing the outer most element's event is handled first and then the inner: the
<div> element's click event will be handled first, then the <p> element's click event.
• With the addEventListener() method you can specify the propagation type by
using the "useCapture" parameter:
addEventListener(event, function, useCapture);
– The default value is false, which will use the bubbling propagation,
– when the value is set to true, the event uses the capturing propagation.
Event Bubbling or Event Capturing
Event Bubbling or Event Capturing
Event Bubbling or Event Capturing
Form Validation
• You have to register a function in
combination with the onsubmit event
of form. The duty of this function is to check
the data which an user has entered in form,
and return true if all the information
entered by the user is valid and vice versa
return false.
• When the user clicks Submit, the function in
combination with the onsubmit event will be
called.
• If the function in combination with
the onsubmit event returns true, the data
of form will be sent to the server and vice
versa the Submit action will be cancelled.
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
Phone Number validation
Phone Number validation
Automatic HTML Form Validation
• HTML form validation can be performed
automatically by the browser:
• If a form field (fname) is empty,
the required attribute prevents this form from
being submitted:
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
Automatic HTML Form Validation
DHTML with JavaScript
• DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic
HTML.
• Dynamic HTML is not a markup or programming language but it is a term
that combines the features of various web development technologies for
creating the web pages dynamic and interactive.
• According to the World Wide Web Consortium (W3C):
"Dynamic HTML is a term used by some vendors to describe the
combination of HTML, style sheets and scripts that allows documents to
be animated."
Features of DHTML
• Its simplest and main feature is that we can create the web page dynamically.
• Dynamic Style is a feature, that allows the users to alter the font, size, color,
and content of a web page.
• It provides the facility for using the events, methods, and properties. And, also
provides the feature of code reusability.
• It also provides the feature in browsers for data binding.
• Using DHTML, users can easily create dynamic fonts for their web sites or web
pages.
• With the help of DHTML, users can easily change the tags and their properties.
Components of Dynamic HTML
• DHTML consists of the following four components or languages:
– HTML 4.0
• HTML is a client-side markup language, which is a core component of the DHTML.
It defines the structure of a web page with various defined basic elements or tags.
– CSS
• CSS stands for Cascading Style Sheet, which allows the web users or developers for
controlling the style and layout of the HTML elements on the web pages.
– JavaScript
• JavaScript is the scripting standard for HTML.
• DHTML is about using JavaScript to control, access and manipulate HTML
elements.
– DOM.
• The HTML DOM is the W3C standard Document Object Model for HTML.
• The HTML DOM defines a standard set of objects for HTML, and a standard way to
access and manipulate them.
• DHTML is about using the DOM to access and manipulate HTML elements.
Components of Dynamic HTML
• JavaScript Alone
• document.write()
– can be used to display dynamic content to a web
page.
• JavaScript and the HTML DOM
– With HTML 4, JavaScript can also be used to change
the inner content and attributes of HTML elements
dynamically.
– To change the content of an HTML element use:
• document.getElementById(id).innerHTML=new HTML
– To change the attribute of an HTML element use:
• document.getElementById(id).attribute=new value
Components of Dynamic HTML
• JavaScript and HTML Events
– New to HTML 4 is the ability to let HTML events
trigger actions in the browser, like starting a
JavaScript when a user clicks on an HTML element.
– To execute code when a user clicks on an element,
use the following event attribute:
• onclick=JavaScript
• JavaScript and CSS
– With HTML 4, JavaScript can also be used to
change the style of HTML elements.
– To change the style of an HTML element use:
• document.getElementById(id).style.property=new style
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
Example to understand how to use
JavaScript in DHTML.
<html>
<head>
<title>DOM programming</title>
</head>
<body>
<h1>Welcome</h1>
<p id = “p1">Hello!</p>
<script style = "text/javascript">
document.getElementById(“p1").innerHTML =
“Welcome u all";
</script>
</body>
</html>
Creating an alert on click of a button.
<html>
<head>
<title>Create an alert</title>
</head>
<body>
<h1 id = "para1">Welcome</h1>
<input type = "Submit" onclick = "Click()"/>
<script style = "text/javascript">
function Click() {
document.getElementById("para1").style.color = "#009900";
window.alert("Color changed to green");
}
</script>
</body>
</html>
<html>
<head>
<title>Validate input data</title>
</head>
<body>
<p>Enter graduation percentage:</p>
<input id="perc">
<button type="button" onclick="Validate()">Submit</button>
<p id="demo"></p>
<script>
function Validate() {
var x, text;
x = document.getElementById("perc").value;
if (isNaN(x) || x < 60)
{
window.alert("Not selected");
}
else
{
document.getElementById("demo").innerHTML = "Selected";
document.getElementById("demo").style.color = "#009900";
}
}
</script>
</body>
</html>
Validate input data using JavaScript.

More Related Content

PPTX
Java script
PPTX
JavaScript New Tutorial Class XI and XII.pptx
PDF
JS BASICS JAVA SCRIPT SCRIPTING
PPTX
HNDIT1022 Week 08, 09 10 Theory web .pptx
PPTX
Final Java-script.pptx
PPT
Java script202
PPT
Java script
PPT
Java script
Java script
JavaScript New Tutorial Class XI and XII.pptx
JS BASICS JAVA SCRIPT SCRIPTING
HNDIT1022 Week 08, 09 10 Theory web .pptx
Final Java-script.pptx
Java script202
Java script
Java script

Similar to CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation (20)

DOC
Java script by Act Academy
PPTX
WTA-MODULE-4.pptx
PDF
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
PDF
Unit 4(it workshop)
PPT
JAVA SCRIPT
PPT
JS-Slides-1hgvhfhgftgfvujguyghvhjbjbnnhg
PDF
8.-Javascript-report powerpoint presentation
DOC
Basics java scripts
PPT
basics of javascript and fundamentals ppt
PPT
JS-Slides_for_begineers_javascript-1.ppt
PPT
JS-Slides-1 (1).ppt vbefgvsdfgdfgfggergertgrtgrtgt
PPT
Javascript overview and introduction to js
PPT
java script programming slide 1 from tn state
PPT
java script programming slide 1 from tn state
DOCX
JavaScript
PPTX
txWelcome to Javascript Welcome to Javascript.pp
PPTX
CHAPTER 3 JS (1).pptx
PPT
Session vii(java scriptbasics)
PDF
Hsc IT Chap 3. Advanced javascript-1.pdf
PPTX
Java script writing javascript
Java script by Act Academy
WTA-MODULE-4.pptx
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
Unit 4(it workshop)
JAVA SCRIPT
JS-Slides-1hgvhfhgftgfvujguyghvhjbjbnnhg
8.-Javascript-report powerpoint presentation
Basics java scripts
basics of javascript and fundamentals ppt
JS-Slides_for_begineers_javascript-1.ppt
JS-Slides-1 (1).ppt vbefgvsdfgdfgfggergertgrtgrtgt
Javascript overview and introduction to js
java script programming slide 1 from tn state
java script programming slide 1 from tn state
JavaScript
txWelcome to Javascript Welcome to Javascript.pp
CHAPTER 3 JS (1).pptx
Session vii(java scriptbasics)
Hsc IT Chap 3. Advanced javascript-1.pdf
Java script writing javascript
Ad

Recently uploaded (20)

PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Digital Logic Computer Design lecture notes
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
composite construction of structures.pdf
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Welding lecture in detail for understanding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Construction Project Organization Group 2.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Digital Logic Computer Design lecture notes
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
OOP with Java - Java Introduction (Basics)
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Internet of Things (IOT) - A guide to understanding
Model Code of Practice - Construction Work - 21102022 .pdf
bas. eng. economics group 4 presentation 1.pptx
composite construction of structures.pdf
Lecture Notes Electrical Wiring System Components
Arduino robotics embedded978-1-4302-3184-4.pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Welding lecture in detail for understanding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Construction Project Organization Group 2.pptx
Ad

CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation

  • 1. Mr. K. Chairmadurai, Assistant Professor/ CSE Adhiparasakthi Engineering College, Melmaruvathur.
  • 2. Syllabus : Java Script JSON -An introduction to JavaScript -JavaScript DOM Model -Date and Objects, -Regular Expressions -Exception Handling -Validation -Built-in objects -Event Handling - DHTML with JavaScript -Introduction – Syntax – Function Files – Http Request –SQL
  • 3. Introduction to JavaScript • JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout & design of web pages 3. JavaScript to program the behavior of web pages • JavaScript is a case-sensitive language.
  • 4. Introduction to JavaScript • JavaScript is a client-side, object-based scripting language that is used to handle and validate client-side data. JavaScript is also used for making the user interface of the web pages more dynamic. • JavaScript is a lightweight scripting language based on ECMA Script standards. It executes on the browser and therefore reduces the load on the server. • It is an interpreted language which means the script written inside Javascript is processed line by line and is not compiled before processing. These Scripts are interpreted by JavaScript interpreter which is a built-in component of the Web browser. • JavaScript is Platform Independent, which means you need to write the script once and can run it on any platform or browser without affecting the output of the Script.
  • 5. Introduction to JavaScript • Browsers use their own JavaScript Engines to execute the JavaScript code. • Some commonly used browsers are listed below: – Chrome uses a V8 engine. – Firefox uses the SpiderMonkey engine. – Microsoft Edge uses the ChakraCore engine. – Safari uses the SquirrelFish engine.
  • 6. JavaScript Features • Light Weight – JavaScript is a lightweight scripting language because it is made for data handling at the browser level only. • Dynamically Typed – JavaScript supports dynamic typing which means types of the variable are defined based on the stored value. • Object-Based – JavaScipt is an object-based scripting language that provides built-in objects like String, Math, Date, etc. • Functional – This implies that JavaScript uses a functional approach, even objects are created from the constructor functions and each constructor function represents a unique object-type. • Platform Independent – you can write your JavaScript applications and run them on any platform or any browser without affecting the output of the Script. • Prototype-based – In JavaScript, each constructor function is associated with a prototype object.
  • 7. JavaScript Features • Interpreted – JavaScript is an interpreted language which means the script written inside javascript is processed line by line. These scripts are interpreted by JavaScript interpreter which is a built-in component of the Web browser. • Asynchronous – JavaScript can be used to do complex processing asynchronously which means that the whole page will not have to wait for the JavaScript processing, and once the script processing completes we can easily modify the HTML code to show or hide data. • Client-side Validations – This is a feature which is available in JavaScript since forever and is still widely used because every website has a form in which users enter values, and to make sure that users enter the correct value, we must put proper validations in place, both on the client-side and on the server-side. JavaScript is used for implementing client-side validations. • More control in Browser – JavaScript being a client-side language provides many features that help developers to divide processing between browser and server hence reducing the load on servers by having basic processing, validations, temporary data saving using cookies, etc on the
  • 8. Advantages of JavaScript • JavaScript makes the webpage more interactive and dynamic. • By using JavaScript you can make your webpage to give immediate feedback to the user so that they would not have to reload the page. • You can use JavaScript to perform actions based on how the user interacts with your webpage using the events generated like a mouse click, form submit, button click and a lot more. • JavaScript can save server traffic by validating the user inputs before even sending data to the server. • JavaScript can be used to store client-side cookies to store data on the client-side and then read them or delete them. • JavaScript can be used to make async HTTP calls to load data from the server.
  • 9. Applications of JavaScript • Client-side validation, • Manipulating HTML Pages • Dynamic drop-down menus, • Displaying date and time, • User Notifications • Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and prompt dialog box), • Displaying clocks etc.
  • 10. JavaScript Output • JavaScript can "display" data in different ways: • Writing into the HTML output using document.write(). • Writing into an HTML element, using innerHTML. • Writing into an alert box, using window.alert(). • Writing into the browser console, using console.log().
  • 11. Using innerHTML • To access an HTML element, JavaScript can use the document.getElementById(id) method. • The id attribute defines the HTML element. The innerHTML property defines the HTML content:
  • 12. Using document.write() • JavaScript lets you write any output into the HTML webpage by using the document.write() method. • By using this method you can directly write output to the HTML page. • Using document.write() after an HTML document is loaded, will delete all existing HTML • The document.write() method should only be used for testing.
  • 13. Using window.alert() • There are certain websites that give you alert messages when you access them or when you perform some action you see the output message in alert boxes. • You can also make your webpage to send alert messages to notify something to the user using JavaScript, to use this feature you need to use the window.alert() method.
  • 14. What JavaScript can do • JavaScript Can Change HTML Content – document.getElementById("demo").innerHTML = "Hello JavaScript"; • JavaScript Can Change HTML Attribute Values – document.getElementById('myImage').src='pic_bulbon.gif' • JavaScript Can Change HTML Styles (CSS) – document.getElementById("demo").style.fontSize = "35px"; • JavaScript Can Hide HTML Elements – document.getElementById("demo").style.display = "none";
  • 15. JavaScript Where To Write <Script> tag • In HTML, JavaScript code is inserted between <script> and </script> tags. <script ...> JavaScript code </script> • Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both
  • 16. < Script> Attributes • Src - It specifies the uniform source locator(URL) of a file that contains the script. • Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
  • 17. Include JavaScript in an HTML file • Script in <head>...</head> section. • Script in <body>...</body> section. • Script in <body>...</body> and <head>...</head> sections. • Script in an external file and then include in <head>...</head> section.
  • 18. <html> <head> <script> document.write("Hai World!") </script> <head> <body> <p> Welcome to Java Script </p> </body> </html> JavaScript in <head>...</head> section
  • 20. <html> <head> <script> document.write("I am in Head Tag") </script> </head> <body> <br> <script> document.write("I am in Body Tag") </script> </body> </html> JavaScript in <head> and<body> section
  • 21. document.write("I am printing from External script file") JavaScript in External File <html> <head> <script src = "external.js" > </script> </head> <body> </body> </html> sample.html external.js
  • 22. Advantages of External JavaScript File • It separates the HTML and JavaScript code and makes the code look clean and easy to understand also maintain. • External JavaScript code can be reused in multiple HTML webpages. • External JavaScript code can be cached in the browser. • Once cached the browser will not load the JavaScript file again and again and will use the cached version of it. This will make your webpage loading fast.
  • 23. Basic JavaScript Syntax JavaScript syntax is the set of rules, how JavaScript programs are constructed:
  • 24. Basic JavaScript Syntax Notice that there is no main() function/method
  • 25. Basic JavaScript Syntax Comments like Java/C++ (/* */ also allowed) • Comments refer to the text or code in a program that is ignored at the time of executing the program. • Comments are used to provide additional information in the code, such as the description of code. • And it is considered as good practice to add comments to your code. Single line comments start with //. Multi-line comments start with /* and end with */.
  • 26. Basic JavaScript Syntax Variable declarations: - Not required - Data type not specified • In a programming language, variables are used to store data values. • JavaScript uses the keywords var, let and const to declare variables. • An equal sign is used to assign values to variables.
  • 27. Basic JavaScript Syntax Semi-colons are usually not required, but always allowed at statement end • Semicolons separate JavaScript statements. • Add a semicolon at the end of each executable statement
  • 28. Basic JavaScript Syntax Arithmetic operators same as Java/C++ JavaScript uses arithmetic operators ( + - * / ) to compute values: JavaScript uses an assignment operator ( = ) to assign values to variables: An expression is a combination of values, variables, and operators, which computes to a value.
  • 29. Basic JavaScript Syntax String concatenation operator as well as addition
  • 30. Basic JavaScript Syntax Arguments can be any expressions Argument lists are comma-separated
  • 31. Basic JavaScript Syntax Object dot notation for method calls as in Java/C++
  • 32. Basic JavaScript Syntax Many control constructs and use of { } identical to Java/C++
  • 33. Basic JavaScript Syntax Most relational operators syntactically same as Java/C++
  • 34. Basic JavaScript Syntax Automatic type conversion: guess is String, thinkingOf is Number
  • 35. JavaScript Variables • Variables are containers for storing data (storing data values). • 4 Ways to Declare a JavaScript Variable: – Using var – Using let – Using const – Using nothing
  • 36. JavaScript Variables var x = 5; var y = 6; var z = x + y; let x = 5; let y = 6; let z = x + y; x = 5; y = 6; z = x + y; const price1 = 5; const price2 = 6; let total = price1 + price2;
  • 37. JavaScript Data Types • JavaScript Data types are used to identify the type of data that is stored inside a variable during the script execution. • As we have already specified about the Dynamic Typed JavaScript feature so we do not have to specify the data type of the variable while declaring it. • JavaScript broadly supports three types of Data types, they are: • Primitive Type • Reference Type • Special Data Type
  • 38. JavaScript Primitive Data Type • JavaScript Primitive data types can be classified further into the following types: – String Data Type – Boolean Data Type – Number Data Type
  • 39. JavaScript Composite(Reference) Data types • These data types can hold collections of values and more complex entities. • It is further divided into Object, Array and Function. – Object data type Array data type Function data type • In JavaScript, an object data type is used to store the collection of data. Object's properties are written as key:value pairs, which are separated by commas and enclosed within curly braces {}. • The key (name) must always be a string, but the value can be of any data type. • JavaScript Array data type is written inside a pair of square brackets [] and is used to store multiple values of the same datatype be it strings, numbers etc. var welcome = function() { return "Welcome!"; }
  • 40. JavaScript Special Data types • Undefined Data type – When a variable is just declared and is not assigned any value, it has undefined as its value. – Yes, undefined is a valid data type in JavaScript and it can have only one value which is undefined. • Null Data type – JavaScript Null data type is used to represent no value. It is not similar to undefined, and neither it is similar to empty value or zero value. – The Null datatype means, the variable has been defined but it contains no value. – The Null data type can have only one value, which is null.
  • 41. Variables and Data Types • The typeof operator in JavaScript can be used to check the data type of any variable. • typeof operator returns string related to data type – Syntax: typeof expression • Example:
  • 43. JavaScript Operators • An operator is a symbol that is reserved for special tasks or operations. • Operators are used to performing operations on the operands. • The operands can be variables or numeric literals or string literals. • An operator can work on one or more than one operand. • JavaScript supports a rich set of operators. • These operators perform a specific task and every operator has different properties. • The list of operators is given below: • Arithmetic Operators • Relational Operators • Bitwise Operators • Logical Operators • Assignment Operators • String Operators
  • 53. JavaScript Functions • JavaScript function is a set of statements that are used to perform a specific task. • It can take one or more input and can return output as well. • A JavaScript function is a block of code designed to perform a particular task. • A JavaScript function is executed when "something" invokes it (calls it).
  • 54. Structure of a JavaScript function
  • 55. JavaScript function - Example <script type = "text/javascript"> function welcomeMsg(name) // Function definition { document.write("Hello " + name + " welcome to javascript"); } var nameVal= “CSE"; // creating a variable welcomeMsg(nameVal); // calling the function </script>
  • 59. JavaScript Objects • In JavaScript, we can define an object as a collection of properties that are defined as a key-value pair, where the key is the generic name of the object feature which can be assigned a value. • In JavaScript, an object is a standalone entity where the properties of the object define the characteristics of the object. – For example, if we consider a mobile phone as an object then its properties are its color, screen size, brand name, operating system, RAM, Memory, etc. All these properties define the characteristics of a mobile phone. • The property of an object is a key:value pair, where key refers to a variable, and value refers to any type of value associated with the key. The value can be of any type like a number, string, or even an array, or another object.
  • 60. Creating Objects in JavaScript • We can create an object in JavaScript either by using – the constructor function or – the object literal.
  • 61. Creating Objects in JavaScript JavaScript Object Using Object Literal Syntax JavaScript Object Using Object Constructor
  • 62. Accessing Object Properties • objectName.propertyName • objectName["propertyName"]
  • 63. Add new Property to JavaScript Object
  • 64. Remove and update Property of a JavaScript Object
  • 66. Accessing Object Properties from object literals
  • 67. Accessing Object Properties from object constructor
  • 68. Add new Property to JavaScript Object
  • 69. By using an Object constructor using this keyword • Here, you need to create function with arguments. • Each argument value can be assigned in the current object by using this keyword. • The this keyword refers to the current object. • Here this keyword is used to refer to the object that has been passed to a function
  • 70. By using an Object constructor using this keyword
  • 71. By using an Object constructor using this keyword
  • 72. By using an Object constructor using this keyword
  • 73. Creating Method in JavaScript Object • A method is a function associated with an object. • Methods are defined just as normal JavaScript functions are defined, except that they have to be assigned to an object as a property. • But before defining method, we need to add property in the function with same name as method.
  • 76. JavaScript Built-in Objects • JavaScript has rich set of built-in objects that can be used to deal with various types of collections. • Some commonly used built-in types are listed below. • String • RegExp • Boolean • Number • Array • Math • Date
  • 77. JavaScript Boolean Object • JavaScript Boolean is an object that represents value in two states: true or false. • It is used to create a Boolean object which holds true or false value, depending upon the value used while creating the Boolean object. • The Boolean object's true and false values are different from the primitive boolean type's true and false values. – The Boolean object returns false when it is passed with values such as 0, -0, an empty string(""), false, null, undefined, or Not a Number(NaN) while creating the Boolean object. – Apart from all these values which set the initial value as false for the Boolean object, all other values, even an empty array([]), empty object({}) or the string "false", will set the initial value for the Boolean object as true.
  • 81. Methods of Boolean Object • The following are some of the commonly used methods of the Boolean object. – toString(): converts the boolean value into a string and returns the string. – valueOf(): returns the primitive value of a Boolean object.
  • 82. JavaScript Number Object • JavaScript Number is a built-in wrapper object which is used to work with numerical values. • A Number object can be created using the Number() constructor. • All numbers are 64 bit(8 bytes) floating-point numbers. Unlike C or C++, there are no data types like integer, float, etc, to define numbers in JavaScript
  • 83. Creating JavaScript Number Object 290.78 object
  • 88. JavaScript Math Object • In JavaScript, Math is a built-in object which includes properties and methods for mathematical operations. • We can use the Math object to perform simple and complex arithmetic operations. • Note: Math works with the JavaScript Number type only. • In Math object, All the properties and methods are static. So, we don't need to create its object to use its property or method. Also, even if we want, we cannot create an object as Math is not a constructor function.
  • 94. JavaScript Date Object • JavaScript Date object is a built-in object which is used to deal with date and time. • It stores a Number which represents milliseconds for the Unix Timestamp(which is nothing but milliseconds passed since 1 January 1970 UTC). • We can use it to create a new date, format a date, get elapsed time between two different time values, etc. • It also helps to get a date value using milliseconds number and we can get a date based on the different timezones as well. • The Date object use browser's date timezone by default and display date in the text format. • The Date object can be created using the Date constructor function.
  • 95. Creating the JavaScript Date Object • new Date( ) • new Date(milliseconds) • new Date(datestring) • New Date(year,month,date[,hour,minute,second,millisecond ]) • create a new Date object with the current date and time stored in it. • string formats to create a date object. • Date() constructor can take 7 arguments to create a date, which is: year, month, day, hour, minute, second, and millisecond. • get a date by just passing milliseconds Tue May 05 2020 21:16:17 GMT+0530 (India Standard Time) Wed Feb 13 1991 06:44:00 GMT+0530 (India Standard Time) Wed Feb 13 1991 06:44:00 GMT+0530 (India Standard Time) Tue Dec 25 2018 12:25:12 GMT+0530 (India Standard Time) Fri Nov 05 2027 01:03:20 GMT+0530 (India Standard Time)
  • 99. JavaScript Regular Expression (Regex) • In JavaScript, a Regular Expression (RegEx) is an object that describes a sequence of characters used for defining a search pattern. /^a...s$/ The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and ending with s. A pattern defined using RegEx can be used to match against a string. Expression String Matched? /^a...s$/ abs No match alias Match abyss Match Alias No match An abacus No match
  • 100. Creating a regular expression • There are two ways you can create a regular expression in JavaScript. • Using a regular expression literal: The regular expression consists of a pattern enclosed between slashes. • Using the RegExp() constructor function: You can also create a regular expression by calling the RegExp() constructor function.
  • 101. Specify Pattern Using RegEx - Quantifiers • In the above example (/^a...s$/), ^ and $ are quantifiers. • When we want to concatenate a regular expression with itself multiple times, we can use the quantifier shorthand notation [] . ^ $ * + ? {} () |
  • 102. [] Square brackets • Square brackets specify a set of characters you wish to match. • Here, [abc] will match if the string you are trying to match contains any of the a, b or c. Expression String Matched? [abc] a 1 match ac 2 matches Hey Jude No match abc de ca 5 matches
  • 103. [] Square brackets • You can also specify a range of characters using - inside square brackets. – [a-e] is the same as [abcde]. – [1-4] is the same as [1234]. – [0-39] is the same as [01239]. • You can complement (invert) the character set by using caret ^ symbol at the start of a square-bracket. – [^abc] means any character except a or b or c. – [^0-9] means any non-digit character.
  • 104. . Period • A period matches any single character (except newline 'n'). Expression String Matched? .. a No match ac 1 match acd 1 match acde 2 matches (contains 4 characters)
  • 105. ^ Caret • The caret symbol ^ is used to check if a string starts with a certain character. Expression String Matched? ^a a 1 match abc 1 match bac No match ^ab abc 1 match acb No match (starts with a but not followed by b)
  • 106. $ Dollar • The dollar symbol $ is used to check if a string ends with a certain character. Expression String Matched? a$ a 1 match formula 1 match cab No match
  • 107. * Star • The star symbol * matches zero or more occurrences of the pattern left to it. Expression String Matched? ma*n mn 1 match man 1 match mann 1 match main No match (a is not followed by n) woman 1 match
  • 108. + Plus • The plus symbol + matches one or more occurrences of the pattern left to it. Expression String Matched? ma+n mn No match (no a character) man 1 match mann 1 match main No match (a is not followed by n) woman 1 match
  • 109. ? Question Mark • The question mark symbol ? matches zero or one occurrence of the pattern left to it. Expression String Matched? ma?n mn 1 match man 1 match maan No match (more than one a character) main No match (a is not followed by n) woman 1 match
  • 110. {} Braces • Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left to it. Expression String Matched? a{2,3} abc dat No match abc daat 1 match (at daat) aabc daaat 2 matches (at aabc and daaat) aabc daaaat 2 matches (at aabc and daaaat)
  • 111. | Alternation • Vertical bar | is used for alternation (or operator). Expression String Matched? a|b cde No match ade 1 match (match at ade) acdbea 3 matches (at acdbea)
  • 112. () Group • Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that matches either a or b or c followed by xz Expression String Matched? (a|b|c)xz ab xz No match abxz 1 match (match at abxz) axz cabxz 2 matches (at axzbc cabxz)
  • 114. Special Sequences - Meta Characters • Special sequences make commonly used patterns easier to write. • Meta characters are characters that are interpreted in a special way by a RegEx engine. • A - Matches if the specified characters are at the start of a string. Expression String Matched? Athe the sun Match In the sun No match
  • 115. b • b - Matches if the specified characters are at the beginning or end of a word. Expression String Matched? bfoo football Match a football Match foob a football No match the foo Match the afoo test Match the afootest No match
  • 116. B • B - Opposite of b. Matches if the specified characters are not at the beginning or end of a word. Expression String Matched? Bfoo football No match a football No match fooB a football Match the foo No match the afoo test No match the afootest Match
  • 117. d • d - Matches any decimal digit. Equivalent to [0-9] Expression String Matched? d 12abc3 3 matches (at 12abc3) JavaScript No match
  • 118. D • D - Matches any non-decimal digit. Equivalent to [^0-9] Expression String Matched? D 1ab34"50 3 matches (at 1ab34"50) 1345 No match
  • 119. s • s - Matches where a string contains any whitespace character. Expression String Matched? s JavaScript RegEx 1 match JavaScriptRegEx No match
  • 120. S • S - Matches where a string contains any non- whitespace character. Expression String Matched? S a b 2 matches (at a b)
  • 121. w • w - Matches any alphanumeric character (digits and alphabets). • Equivalent to [a-zA-Z0-9_]. • By the way, underscore _ is also considered an alphanumeric character. Expression String Matched? w 12&": ;c 3 matches (at 12&": ;c) %"> ! No match
  • 122. W • W - Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0-9_] Expression String Matched? W 1a2%c 1 match (at 1a2%c) JavaScript No match
  • 123. Z • Z - Matches if the specified characters are at the end of a string Expression String Matched? JavaScriptZ I like JavaScript 1 match I like JavaScript Programming No match JavaScript is fun No match
  • 124. Regular Expression Flags Modifier • Flags are used with regular expressions that allow various options such as global search, case-insensitive search, etc. • They can be used separately or together.
  • 125. JavaScript Regular Expression Methods • In JavaScript, you can use regular expressions with RegExp() methods: – test() and exec(). • There are also some string methods that allow you to pass RegEx as its parameter. • They are: – match(), replace(), search(), and split().
  • 126. JavaScript Regular Expression Methods Method Description exec() Executes a search for a match in a string and returns an array of information. It returns null on a mismatch. test() Tests for a match in a string and returns true or false. match() Returns an array containing all the matches. It returns null on a mismatch. matchAll() Returns an iterator containing all of the matches. search() Tests for a match in a string and returns the index of the match. It returns -1 if the search fails. replace() Searches for a match in a string and replaces the matched substring with a replacement substring. split() Break a string into an array of substrings.
  • 131. JavaScript Exception Handling • An Exception is an error that occurs at the time of execution(runtime) due to an illegal operation when a program is syntactically correct. – For example, whenever you try to reference an undefined variable or call a non-existent method; an exception will occur. • The try, catch and finally blocks are used to handle exceptions (a type of an error).
  • 132. Types of Errors • While coding, there can be three types of errors in the code: • Syntax Error: When a user makes a mistake in the pre- defined syntax of a programming language, a syntax error may appear. • Runtime Error: When an error occurs during the execution of the program, such an error is known as Runtime error. The codes which create runtime errors are known as Exceptions. Thus, exception handlers are used for handling runtime errors. • Logical Error: An error which occurs when there is any logical mistake in the program that may not produce the desired output, and may terminate abnormally. Such an error is known as Logical error.
  • 133. Throw, and Try...Catch...Finally • The try statement defines – a code block to run (to try). • The catch statement defines – a code block to handle any error. • The finally statement defines – a code block to run regardless of the result. • The throw statement defines – a custom error.
  • 134. JavaScript try and catch • The try statement allows you to define a block of code to be tested for errors while it is being executed. • The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. • The JavaScript statements try and catch come in pairs:
  • 135. JavaScript try...catch...finally Statement • You can also use the try...catch...finally statement to handle exceptions. • The finally block executes both when the code runs successfully or if an error occurs. try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result }
  • 136. JavaScript throw Statement • In JavaScript, the throw statement handles user- defined exceptions. • We can use the throw statement in our JavaScript code to throw a custom error/exception where we can provide a message while throwing the error. • This message can be a string message, a number or any boolean type(true or false). • throw expression; – Here, expression specifies the value of the exception. • The expression can be string, boolean, number, or object value. •
  • 137. The Error Object • JavaScript has a built in error object that provides error information when an error occurs. • The error object provides two useful properties: name and message.
  • 145. Document Object Model in JavaScript • JavaScript can access all the elements in a webpage making use of Document Object Model (DOM). • In fact, the web browser creates a DOM of the webpage when the web page is loaded. • The Document Object Model (DOM) is an application programming interface (API) for manipulating HTML documents. • The DOM represents an HTML document as a tree of nodes. • The DOM provides functions that allow you to add, remove, and modify parts of the document effectively. • Note that the DOM is cross-platform and language-independent ways of manipulating HTML and XML documents. • The HTML DOM model is constructed as a tree of Objects
  • 148. Document Object Model in JavaScript • 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
  • 149. What is the DOM? • The DOM is a W3C (World Wide Web Consortium) standard. • The DOM defines a standard for accessing documents: • "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." • The W3C DOM standard is separated into 3 different parts: – Core DOM - standard model for all document types – XML DOM - standard model for XML documents – HTML DOM - standard model for HTML documents
  • 150. What is the HTML DOM? • The HTML DOM is a standard object model and programming interface for HTML. • It defines: – The HTML elements as objects – The properties of all HTML elements – The methods to access all HTML elements – The events for all HTML elements • The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
  • 151. A document as a hierarchy of nodes • The DOM represents an HTML document as a hierarchy of nodes. • Consider the following HTML document:
  • 152. DOM Nodes • With the HTML DOM, you can navigate the node tree using node relationships. • According to the W3C HTML DOM standard, everything in an HTML document is a node: – The entire document is a document node – Every HTML element is an element node – The text inside HTML elements are text nodes – Every HTML attribute is an attribute node – All comments are comment nodes • With the HTML DOM, all nodes in the node tree can be accessed by JavaScript. • New nodes can be created, and all nodes can be modified or deleted.
  • 153. Relationships between nodes • An HTML document can be represented as a tree of nodes, like a traditional family tree. • Each markup can be represented as a node with a specific node type. • The node is the generic type of element. • Element is a specific type of node with the node type Node.ELEMENT_NODE. • In the DOM tree, a node has relationships with other nodes.
  • 154. Relationships between nodes <html> <head> <title>DOM Tutorial</title> </head> <body> <h1>DOM Lesson one</h1> <p>Hello world!</p> </body> </html> •<html> is the root node •<html> has no parents •<html> is the parent of <head> and <body> •<head> is the first child of <html> •<body> is the last child of <html> •<head> has one child: <title> •<title> has one child (a text node): "DOM Tutorial" •<body> has two children: <h1> and <p> •<h1> has one child: "DOM Lesson one" •<p> has one child: "Hello world!" •<h1> and <p> are siblings
  • 155. Navigating Between Nodes • You can use the following node properties to navigate between nodes with JavaScript: – parentNode - childNodes[nodenumber] – firstChild - lastChild – nextSibling - previousSibling – InnerHTML - to retrieve the content of an HTML element. – document.body - The body of the document – document.documentElement - The full document – nodeName property specifies the name of a node. – nodeName is read-only – nodeName of an element node is the same as the tag name – nodeName of an attribute node is the attribute name – nodeName of a text node is always #text – nodeName of the document node is always #documen – nodeValue property specifies the value of a node. – nodeValue for element nodes is null – nodeValue for text nodes is the text itself – nodeValue for attribute nodes is the attribute value – nodeType property is read only. It returns the type of a node.
  • 160. The HTML DOM Document Object • 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. – Finding HTML Elements – Changing HTML Elements – Adding and Deleting Elements
  • 162. JavaScript getElementById • The document.getElementById() method returns an Element object that represents an HTML element with an id that matches a specified string. • If the document has no element with the specified id, the document.getElementById() returns null. • Because the id of an element is unique within an HTML document, the document.getElementById() is a quick way to access an element. • If the HTML document has multiple elements with the same id, the document.getElementById() method returns the first element it encounters.
  • 165. JavaScript getElementsByTagName • The getElementsByTagName() is a method of the document object or a specific DOM element. • The getElementsByTagName() method accepts a tag name and returns a live HTMLCollection of elements with the matching tag name in the order which they appear in the document. • The return collection of the getElementsByTagName() is live, meaning that it is automatically updated when elements with the matching tag name are added and/or removed from the document. • Note that the HTMLCollection is an array-like object, like arguments object of a function.
  • 167. JavaScript getElementsByClassName • The getElementsByClassName() method returns an array-like of objects of the child elements with a specified class name. • The getElementsByClassName() method is available on the document element or any other elements.
  • 169. JavaScript querySelector • If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method. • The querySelector() finds the first element that matches a CSS selector or a group of CSS selectors. • The querySelectorAll() finds all elements that match a CSS selector or a group of CSS selectors. • A CSS selector defines elements to which a CSS rule applies.
  • 174. Changing HTML Elements • The HTML DOM allows JavaScript to change the content of HTML elements. • The easiest way to modify the content of an HTML element is by using the innerHTML property.
  • 175. Changing HTML Content innerHTML property <html> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "New text!"; </script> </body> </html>
  • 176. Changing HTML Content innerHTML property <!DOCTYPE html> <html> <body> <h1 id="id01">Old Heading</h1> <script> const element = document.getElementById("id01"); element.innerHTML = "New Heading"; </script> </body> </html>
  • 177. Changing the Value of an Attribute document.getElementById(id).attribute = new value
  • 180. Adding and Deleting Elements Property/Method Description createElement() Create a new element node createTextNode() Create a new text node node.textContent Get or set the text content of an element node node.innerHTML Get or set the HTML content of an element
  • 181. Adding and Deleting Elements Property/Method Description node.appendChild() Add a node as the last child of a parent element node.insertBefore() Insert a node into the parent element before a specified sibling node node.replaceChild() Replace an existing node with a new node Inserting Nodes into the DOM Method Description node.removeChild() Remove child node node.remove() Remove node Removing Nodes from the DOM
  • 182. Creating New HTML Elements (Nodes) • To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
  • 186. Replacing HTML Elements To replace an element to the HTML DOM, use the replaceChild() method:
  • 187. JavaScript Events • The change in the state of an object is known as an Event. • In html, there are various events which represents that some activity is performed by the user or by the browser. • When JavaScript code is included in HTML, JavaScript react over these events and allow the execution. This process of reacting over the events is called Event Handling. • Thus, JavaScript handles the HTML events via Event Handlers. – For example, when a user clicks over the browser, add js code, which will execute the task to be performed on the event.
  • 193. Focus
  • 195. Load
  • 196. JavaScript Event Handlers • Event handlers can be used to handle and verify user input, user actions, and browser actions: – Things that should be done every time a page loads – Things that should be done when the page is closed – Action that should be performed when a user clicks a button – Content that should be verified when a user inputs data • Many different methods can be used to let JavaScript work with events: – HTML event attributes can execute JavaScript code directly – HTML event attributes can call JavaScript functions – You can assign your own event handler functions to HTML elements
  • 198. JavaScript addEventListener() • The addEventListener() method is used to attach an event handler to a particular 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.
  • 199. addEventListener() - Syntax • The first parameter is the type of the 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. element.addEventListener(event, function, useCapture);
  • 200. Add an Event Handler to an Element
  • 201. Add an Event Handler to an Element
  • 202. 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:
  • 203. Add Many Event Handlers to the Same Element
  • 204. Add Many Event Handlers to the Same Element
  • 205. Event Bubbling or Event Capturing • There are two ways of event propagation in the HTML DOM, – bubbling and capturing. • Event propagation is a way of defining the element order when an event occurs. • If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which element's "click" event should be handled first? – In bubbling the inner most element's event is handled first and then the outer: the <p> element's click event is handled first, then the <div> element's click event. – In capturing the outer most element's event is handled first and then the inner: the <div> element's click event will be handled first, then the <p> element's click event. • With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter: addEventListener(event, function, useCapture); – The default value is false, which will use the bubbling propagation, – when the value is set to true, the event uses the capturing propagation.
  • 206. Event Bubbling or Event Capturing
  • 207. Event Bubbling or Event Capturing
  • 208. Event Bubbling or Event Capturing
  • 209. Form Validation • You have to register a function in combination with the onsubmit event of form. The duty of this function is to check the data which an user has entered in form, and return true if all the information entered by the user is valid and vice versa return false. • When the user clicks Submit, the function in combination with the onsubmit event will be called. • If the function in combination with the onsubmit event returns true, the data of form will be sent to the server and vice versa the Submit action will be cancelled.
  • 225. Automatic HTML Form Validation • HTML form validation can be performed automatically by the browser: • If a form field (fname) is empty, the required attribute prevents this form from being submitted: <form action="/action_page.php" method="post"> <input type="text" name="fname" required> <input type="submit" value="Submit"> </form>
  • 226. Automatic HTML Form Validation
  • 227. DHTML with JavaScript • DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML. • Dynamic HTML is not a markup or programming language but it is a term that combines the features of various web development technologies for creating the web pages dynamic and interactive. • According to the World Wide Web Consortium (W3C): "Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated."
  • 228. Features of DHTML • Its simplest and main feature is that we can create the web page dynamically. • Dynamic Style is a feature, that allows the users to alter the font, size, color, and content of a web page. • It provides the facility for using the events, methods, and properties. And, also provides the feature of code reusability. • It also provides the feature in browsers for data binding. • Using DHTML, users can easily create dynamic fonts for their web sites or web pages. • With the help of DHTML, users can easily change the tags and their properties.
  • 229. Components of Dynamic HTML • DHTML consists of the following four components or languages: – HTML 4.0 • HTML is a client-side markup language, which is a core component of the DHTML. It defines the structure of a web page with various defined basic elements or tags. – CSS • CSS stands for Cascading Style Sheet, which allows the web users or developers for controlling the style and layout of the HTML elements on the web pages. – JavaScript • JavaScript is the scripting standard for HTML. • DHTML is about using JavaScript to control, access and manipulate HTML elements. – DOM. • The HTML DOM is the W3C standard Document Object Model for HTML. • The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate them. • DHTML is about using the DOM to access and manipulate HTML elements.
  • 230. Components of Dynamic HTML • JavaScript Alone • document.write() – can be used to display dynamic content to a web page. • JavaScript and the HTML DOM – With HTML 4, JavaScript can also be used to change the inner content and attributes of HTML elements dynamically. – To change the content of an HTML element use: • document.getElementById(id).innerHTML=new HTML – To change the attribute of an HTML element use: • document.getElementById(id).attribute=new value
  • 231. Components of Dynamic HTML • JavaScript and HTML Events – New to HTML 4 is the ability to let HTML events trigger actions in the browser, like starting a JavaScript when a user clicks on an HTML element. – To execute code when a user clicks on an element, use the following event attribute: • onclick=JavaScript • JavaScript and CSS – With HTML 4, JavaScript can also be used to change the style of HTML elements. – To change the style of an HTML element use: • document.getElementById(id).style.property=new style
  • 233. Example to understand how to use JavaScript in DHTML. <html> <head> <title>DOM programming</title> </head> <body> <h1>Welcome</h1> <p id = “p1">Hello!</p> <script style = "text/javascript"> document.getElementById(“p1").innerHTML = “Welcome u all"; </script> </body> </html>
  • 234. Creating an alert on click of a button. <html> <head> <title>Create an alert</title> </head> <body> <h1 id = "para1">Welcome</h1> <input type = "Submit" onclick = "Click()"/> <script style = "text/javascript"> function Click() { document.getElementById("para1").style.color = "#009900"; window.alert("Color changed to green"); } </script> </body> </html>
  • 235. <html> <head> <title>Validate input data</title> </head> <body> <p>Enter graduation percentage:</p> <input id="perc"> <button type="button" onclick="Validate()">Submit</button> <p id="demo"></p> <script> function Validate() { var x, text; x = document.getElementById("perc").value; if (isNaN(x) || x < 60) { window.alert("Not selected"); } else { document.getElementById("demo").innerHTML = "Selected"; document.getElementById("demo").style.color = "#009900"; } } </script> </body> </html> Validate input data using JavaScript.