2. Introduction
"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.“
3. JavaScript HTML DOM
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
4. The DOM Programming Interface
The HTML DOM can be accessed with JavaScript (and with other
programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is used to access the properties and
methods of each object.
A property is a value that you can get or set (like changing the content
of an HTML element).
A method is an action you can do (like add or deleting an HTML
element).
6. Example
Method-getElementById( )
The most common way to access an HTML element is to use the id of the
element.
In the example above the getElementById method used id="demo" to find the
element.
Property-innerHTML
The easiest way to get the content of an element is by using the innerHTML
property.
The innerHTML property is useful for getting or replacing the content of HTML
elements.
7. JavaScript HTML DOM Document
The HTML DOM document object is the owner of all other
objects in your web page.
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.
8. Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
9. Changing HTML Elements
Method Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
10. <!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<p > The DOM is very useful.</p>
<p>This is example.</p>
<p id="demo"></p>
<script>
var y = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
'The first paragraph inside "main" is: ' + y[0].innerHTML;
</script>
</body>
</html>
12. Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream
13. <body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
</body>
14. <body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var parent= document.getElementById("div1");
var child = document.getElementById("p1");
parent.insertBefore(para, child);
</script>
</body>
15. <body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var node = document.getElementById("p1");
node.remove ();
</script>
</body>
16. <body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
</body>
17. <body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para, child);
</script> </body>
18. Adding Events Handlers
Method Description
document.getElementById(id).onclick =
function(){code}
Adding event handler code to an onclick event
20. Finding HTML Objects
The first HTML DOM Level 1 (1998), defined 11 HTML objects,
object collections, and properties. These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and
properties were added.
Property Description DOM
document.anchors Returns all <a> elements that have a name attribute 1
document.applets
Returns all <applet> elements (Deprecated in
HTML5)
1
document.baseURI Returns the absolute base URI of the document 3
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.documentElement Returns the <html> element 3
21. Property Description DOM
document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the document server 1
document.domConfig Obsolete. Returns the DOM configuration 3
document.embeds Returns all <embed> elements 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <img> elements 1
document.implementation Returns the DOM implementation 3
document.inputEncoding Returns the document's encoding (character set) 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
document.readyState Returns the (loading) status of the document 3
document.referrer Returns the URI of the referrer (the linking document) 1
document.scripts Returns all <script> elements 3
document.strictErrorChecking Returns if error checking is enforced 3
document.title Returns the <title> element 1
document.URL Returns the complete URL of the document 1
26. Introduction
In JavaScript, almost "everything" is an object.
Booleans can be objects (if defined with the new keyword)
Numbers can be objects (if defined with the new keyword)
Strings can be objects (if defined with the new keyword)
Dates are always objects
Maths are always objects
Regular expressions are always objects
Arrays are always objects
Functions are always objects
Objects are always objects
All JavaScript values, except primitives, are objects.
27. Built-in / Native Objects in JS
JS Array
JS RegExp
JS Date
JS Math
JS Number
JS Boolean
JS Error
JS Global
JS JSON
JS Operators
JS Statements
JS String
28. Objects are Variables
JavaScript variables can contain single values:
Example
var person = "John";
Objects are variables too. But objects can contain many values.
The values are written as name : value pairs (name and value separated by a
colon).
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
29. Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and
functions.
An object method is an object property containing a function
definition.
Example
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
name = person.fullName();
30. JavaScript Keyword new
The following example also creates a new JavaScript object with four
properties:
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
In a constructor function this does not have a value. It is a substitute for
the new object.
The value of this will become the new object when a new object is
created.
31. Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of
person:
var x = person; // This will not create a copy of person.
The object x is not a copy of person. It is person. Both x and person are the
same object.
Any changes to x will also change person, because x and person are the same
object.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
var x = person;
x.age = 10; // This will change both x.age and person.age
32. Object Properties
Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.
Accessing JavaScript Properties
objectName.property // person.age or
objectName["property"] // person["age"] or
objectName[expression] // x = "age"; person[x]
Adding New Properties
person.nationality = "English";
Deleting Properties
delete person.age; // or delete person["age"];
33. The get Keyword
<body>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language;
} };
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
</script>
</body>
34. The set Keyword
<body>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
language : "",
set lang(lang) {
this.language = lang;
} };
// Set a property using set:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
</script></body>
35. Object Constructors
Sometimes we need a "blueprint" for creating many objects of the same "type".
The way to create an "object type", is to use an object constructor function.
In the example above, function Person() is an object constructor function.
Objects of the same type are created by calling the constructor function with the new
keyword:
<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
</script>
36. <body>
<h2>JavaScript Object Constructors</h2>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.nationality = "English"; //new property to a constructor
}
var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML ="My father” + myFather.firstName +
“Nationality is " + myFather.nationality;
</script>
</body>
37. Built-in JavaScript Constructors
var x1 = new Object(); // A new Object object
var x2 = new String(); // A new String object
var x3 = new Number(); // A new Number object
var x4 = new Boolean(); // A new Boolean object
var x5 = new Array(); // A new Array object
var x6 = new RegExp(); // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date(); // A new Date object
The Math() object is not in the list. Math is a global object. The new
keyword cannot be used on Math.
39. Get Date Methods
Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
These methods can be used for getting information from a Date
object
40. <body>
<p>The getFullYear() method returns the full year of a date:</p>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>
</body>
Output:
The getFullYear() method returns the full year of a date:
2018
41. <body>
<p id="demo"></p>
<script>
var d = new Date();
var months =
["January","February","March","April","May","June","July","August","September",
"October","November","December"];
document.getElementById("demo").innerHTML = months[d.getMonth()];
</script>
</body>
Output:
August
42. UTC Date Methods
UTC date methods are used for working with UTC dates (Universal Time Zone dates):
Method Description
getUTCDate() Same as getDate(), but returns the UTC date
getUTCDay() Same as getDay(), but returns the UTC day
getUTCFullYear() Same as getFullYear(), but returns the UTC year
getUTCHours() Same as getHours(), but returns the UTC hour
getUTCMilliseconds() Same as getMilliseconds(), but returns the UTC milliseconds
getUTCMinutes() Same as getMinutes(), but returns the UTC minutes
getUTCMonth() Same as getMonth(), but returns the UTC month
getUTCSeconds() Same as getSeconds(), but returns the UTC seconds
43. Set Date Methods
Set Date methods let you set date values (years, months, days, hours, minutes, seconds,
milliseconds) for a Date Object.
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
44. <body>
<p>Please note that month counts from 0. December is month 11:</p>
<p id="demo"></p>
<script>
var d = new Date();
d.setFullYear(2020, 11, 3);
document.getElementById("demo").innerHTML = d;
</script>
</body>
Output:
Please note that month counts from 0. December is month 11:
Thu Dec 03 2020 10:16:14 GMT+0530 (India Standard Time)
45. Compare Dates
<body>
<p id="demo"></p>
<script>
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today)
{ text = "Today is before January 14, 2100."; }
else { text = "Today is after January 14, 2100."; }
document.getElementById("demo").innerHTML = text;
</script>
</body>
Output:
Today is before January 14, 2100.
47. JS RegExp Object
A regular expression is an object that describes a
pattern of characters.
Regular expressions are used to perform pattern-
matching and "search-and-replace" functions on text.
A regular expression can be a single character, or a
more complicated pattern.
Syntax
/pattern/modifiers;
48. JS RegExp Object
Modifiers are used to perform case-insensitive and global
searches:
Modifier Description
i Perform case-insensitive matching
g
Perform a global match (find all matches rather than
stopping after the first match)
m Perform multiline matching
49. Example
var patt = /Ramco/i
Example:
/Ramco/i is a regular expression.
Ramco is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-
insensitive).
50. Using String Methods
In JavaScript, regular expressions are often used with
the two string methods: search() and replace().
The search() method uses an expression to search for
a match, and returns the position of the match.
var str = "Visit Ramco!";
var n = str.search(“Ramco");
51. Using String Methods
With a Regular Expression
var str = "Visit Ramco";
var n = str.search(/Ramco/i);
The replace() method returns a modified string where
the pattern is replaced.
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, ‘’Ramco");
52. <body>
<p id="demo"></p>
<script>
var str = "Visit Ramco!";
var n = str.search(/Ramco/i);
document.getElementById("demo").innerHTML = n;
var res = str.replace(/Ramco/i, “RIT");
document.getElementById("demo").innerHTML = res;
</script>
</body>
6
Visit RIT!
53. Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
[abc] Find any character between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find any character between the brackets (any digit)
[^0-9]
Find any character NOT between the brackets (any
non-digit)
(x|y) Find any of the alternatives specified
54. <body>
<button onclick="myFunction()">Try
it</button>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
function myFunction() {
var str = "Is this all there is 6789";
var patt = /^(([w]*s?))*$/;
var patt1 = /([^a]|[i-s])/g;
var patt2 = /([h]|[7-9])/;
var patt3 = /([h]|[7-9])/g
var result = str.match(patt);
var result1 = str.match(patt1);
var result2 = str.match(patt2); var result3 = str.match(patt3);
if(str.match(patt))
{ document.getElementById("demo").innerHTML = "1"; }
Else { document.getElementById("demo").innerHTML =
"0"; }
document.getElementById("demo1").innerHTML = result1;
document.getElementById("demo2").innerHTML = result2;
document.getElementById("demo3").innerHTML = result3;
} </script> </body>
OUTPUT
1
I,s, ,t,h,i,s, ,l,l, ,t,h,e,r,e, ,i,s, ,6,7,8,9
h,h
h,h,7,8,9
55. Character Class
In addition to Metacharacters there are some Character Classes are available
Character Class Description
w Find a word character
W Find a non-word character
d Find a digit
D Find a non-digit character
s Find a whitespace character
S Find a non-whitespace character
b Find a match at the beginning of a word
B Find a match not at the beginning of a word
0 Find a NUL character
t Find a tab character
v Find a vertical tab character
56. <body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
function myFunction() {
var str = "Visit Ramco789";
var patt = /w/g;
var patt1 = /bRA/i;
var result = str.match(patt);
var result1 = str.match(patt1);
document.getElementById("demo").innerHTML = result;
document.getElementById("demo1").innerHTML = result1;
}
</script>
</body>
OUTPUT
V,i,s,i,t,R,a,m,c,o,7,8,9
Ra
57. Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n
n*
Matches any string that contains zero or more occurrences of
n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
Quantifiers define quantities:
58. <body>
<button onclick="myFunction()">Try
it</button>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<script>
function myFunction() {
var str = "Hellooo World! Hello Ramco!";
var patt = /o+/g;
var patt1 = /o*/g;
var patt2 = /o?/g;
var patt3 = /o{2}/g;
var patt4 = /l{1,}/g;
var result = str.match(patt);
var result1 = str.match(patt1);
var result2 = str.match(patt2);
var result3 = str.match(patt3);
var result4 = str.match(patt4);
document.getElementById("demo").innerHTML = result;
document.getElementById("demo1").innerHTML = result1;
document.getElementById("demo2").innerHTML = result2;
document.getElementById("demo3").innerHTML = result3;
document.getElementById("demo4").innerHTML = result4;
} </script> </body>
OUTPUT
ooo,o,o,o
,,,,ooo,,,o,,,,,,,,,,o,,,,,,o,,
,,,,o,o,o,,,o,,,,,,,,,,o,,,,,,o,,
oo
ll,l,ll
59. RegExp Object Properties
Property Description
global Checks whether the "g" modifier is set
ignoreCase Checks whether the "i" modifier is set
lastIndex
Specifies the index at which to start the next
match
multiline Checks whether the "m" modifier is set
source Returns the text of the RegExp pattern
var p=new RegExp;
p=/[a-z]/ig;
var r=p.properties;
60. <body> <button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function myFunction() {
var str = "The rain in Spain stays mainly in the plain";
var patt1 = /ain/gm;
var res = patt1.global;
var res1 = patt1.ignoreCase;
var res2 = patt1.source;
document.getElementById("demo").innerHTML = res;
document.getElementById("demo1").innerHTML = res1;
document.getElementById("demo2").innerHTML = res2;
} </script></body>
OUTPUT
true
false
ain
61. RegExp Object Methods
Method Description
compile()
Deprecated in version 1.5. Compiles a regular
expression
exec()
Tests for a match in a string. Returns the first
match
test()
Tests for a match in a string. Returns true or
false
toString()
Returns the string value of the regular
expression
var p=new RegExp;
p=/[a-z]/ig;
var r=p.method();
62. <body> <button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function myFunction() {
var str = "The best things in life are free";
var patt = /est/i; // or new RegExp("est","i");
patt.compile(patt);
var res = patt.exec(str);
var res1 = patt.test(str);
var res2 = patt.toString();
document.getElementById("demo").innerHTML = res;
document.getElementById("demo1").innerHTML = res1;
document.getElementById("demo2").innerHTML = res2;
} </script></body>
OUTPUT
est
true
/est/i
64. Validation
Form validation normally used to occur at the server, after the
client had entered all the necessary data and then pressed the
Submit button.
If the data entered by a client was incorrect or was simply
missing, the server would have to send all the data back to the
client and request that the form be resubmitted with correct
information.
If the data entered by a client was incorrect or was simply
missing, the server would have to send all the data back to the
client and request that the form be resubmitted with correct
information.
This was really a lengthy process which used to put a lot of
burden on the server.
65. JavaScript-Validation
JavaScript provides a way to validate form's data on the
client's computer before sending it to the web server. Form
validation generally performs two functions.
Basic Validation − First of all, the form must be checked to
make sure all the mandatory fields are filled in. It would
require just a loop through each field in the form and
check for data.
Data Format Validation − Secondly, the data that is
entered must be checked for correct form and value. Your
code must include appropriate logic to test correctness of
data.
66. <head> <script>
function validateForm() {
//var x = document.forms["myForm"]["fname"].value; or
var x=document.myForm.fame.value;
if (x == "") {
window.alert("Name must be filled out");
return false;
} }
</script> </head> <body>
<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname" id="fame">
<input type="submit" value="Submit">
</form> </body>
OUTPUT
67. <input type="text" id="numb">
<button type="button"
onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
x = document.getElementById("numb").value;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
} document.getElementById("demo").innerHTML = text;
} </script></body>
OUTPUT
5
Input OK
X
Input not valid
68. Other Validation
Type Pattern
Mobile Number /d{10}/ or /d{3}-d{3}-d{4}$/
Email /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/
Password ^[A-Za-z]w{7,15}$
69. Credit Card Validation
Format of some well-known credit cards.
American Express :- Starting with 34 or 37, length 15 digits.
Visa :- Starting with 4, length 13 or 16 digits.
MasterCard :- Starting with 51 through 55, length 16 digits.
Discover :- Starting with 6011, length 16 digits or starting with 5,
length 15 digits.
Diners Club :- Starting with 300 through 305, 36, or 38, length 14
digits.
JCB :- Starting with 2131 or 1800, length 15 digits or starting with
35, length 16 digits.
70. <script>
function fun() {
var p/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
var t=document.getElementById("y").value;
if(p.test(t))
{ document.getElementById(“para").innerHTML="YES"; }
else
{ document.getElementById(“para").innerHTML=“NO"; } }
</script>
<body>
<input type="text" id="y">
<button type="button" onclick=fun() >Click Me </button>
<p id=“para"></p>
</body>
OUTPUT
5asd@gmail
NO
asd@ert.wer.com
YES
72. JavaScript Errors - Throw and Try to Catch
The try statement lets you test a block of code
for error / define a block of code to be tested for
errors while it is being executed..
The catch statement lets you handle the error
/define a block of code to be executed, if an
error occurs in the try block.
The throw statement lets you create custom
errors.
73. JavaScript Errors - Finally
The finally statement lets you execute code,
after try and catch, regardless of the result.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
75. <body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<p id="p02"></p>
<script>
function myFunction() {
var x;
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high"; }
catch(err) {
document.getElementById("p01").i
nnerHTML = "Input is " + err; }
finally {
document.getElementById("p12").i
nnerHTML="THE END";
} }
</script>
</body>
OUTPUT
Please input a number between 5
and 10:
k
Input is not a number
THE END
76. Error Name Values
Five different values can be returned by the error name
property:
EvalError
Newer versions of JavaScript does not throw any
EvalError.
77. Error Name Values
Range Error
A RangeError is thrown if you use a number that is outside the
range of legal values.
For example: You cannot set the number of significant digits of a
number to 500.
var num = 1;
try {
num.toPrecision(500); // A number cannot have 500
significant digits
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
78. Error Name Values
Reference Error
A ReferenceError is thrown if you use (reference) a variable that has
not been declared:
Example
var x;
try {
x = y + 1; // y cannot be referenced (used)
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
79. Error Name Values
Syntax Error
A SyntaxError is thrown if you try to evaluate code with a syntax
error.
Example
try {
eval("alert('Hello)"); // Missing ' will produce an error
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
80. Error Name Values
Type Error
A TypeError is thrown if you use a value that is outside the range
of expected types:
Example
var num = 1;
try {
num.toUpperCase(); // You cannot convert a number to
upper case
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
81. Error Name Values
URI (Uniform Resource Identifier) Error
A URIError is thrown if you use illegal characters in a URI function:
Example
try {
decodeURI("%%%"); // You cannot URI decode percent
signs
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
83. JS MATH
Math is a built-in object that has properties and
methods for mathematical constants and functions.
Not a function object.
Unlike the other global objects, Math is not a
constructor.
All properties and methods of Math are static.
You refer to the constant pi as Math.PI and you call
the sine function as Math.sin(x), where x is the
method's argument.
86. Math Properties (Constants)
JavaScript provides 8 mathematical constants that can be
accessed with the Math object:
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of ½
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
88. Events
HTML events are "things" that happen to HTML
elements.
When JavaScript is used in HTML pages, JavaScript can
"react" on these events.
An HTML event can be something the browser does, or
something a user does.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
89. Events
HTML allows event handler attributes, with JavaScript
code, to be added to HTML elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
91. Common HTML Events
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover
The user moves the mouse over an HTML
element
onmouseout
The user moves the mouse away from an
HTML element
Onkeydown/up The user pushes a keyboard key
Onload The browser has finished loading the page
92. Onchange
The onchange event occurs when the value of an
element has been changed.
For radiobuttons and checkboxes, the onchange event
occurs when the checked state has been changed.
Tip: This event is similar to the oninput event. The
difference is that the oninput event occurs immediately
after the value of an element has changed, while
onchange occurs when the element loses focus, after
the content has been changed. The other difference is
that the onchange event also works on <select>
elements.
93. Onchange
<body>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
</select>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x; }
</script></body>
94. Onchange-HTML
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
95. Onchange-JS
<body>
Enter your name: <input type="text" id="fname">
<script>
document.getElementById("fname").onchange=function(){myFunction()};
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
96. Onchange-JS(addEventListener)
<body>
Enter your name: <input type="text" id="fname">
<script>
document.getElementById("fname").addEventListener("change",
myFunction);
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
97. Onclick
In JavaScript, using the addEventListener() method:
object.addEventListener("click", myScript);
In JavaScript:
object.onclick = function(){myScript};
In HTML:
<element onclick="myScript">
99. Onmouseover and Onmouseout
<body>
<h1 id="demo" onmouseover="Over()" onmouseout="Out()">Mouse over
me</h1>
<script>
function Over() {
document.getElementById("demo").style.color = "red";
}
function Out() {
document.getElementById("demo").style.color = "black";
} </script>
</body>
100. DHTML JavaScript
HTML stands for Dynamic HTML. Dynamic means that the content of
the web page can be customized or changed according to user inputs
i.e. a page that is interactive with the user. In earlier times, HTML was
used to create a static page.
It only defined the structure of the content that was displayed on the
page. With the help of CSS, we can beautify the HTML page by
changing various properties like text size, background color etc.
The HTML and CSS could manage to navigate between static pages but
couldn’t do anything else.
If 1000 users view a page that had their information for eg. Admit card
then there was a problem because 1000 static pages for this application
build to work. As the number of users increase, the problem also
increases and at some point it becomes impossible to handle this
problem.
101. JavaScript and the HTML DOM
With HTML , 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
102. JavaScript and HTML Events
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
103. JavaScript and CSS
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