JavaScript
Advanced Concepts
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
1 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Object Oriented Programming (JavaScript)
List of Modules
No. MODULE TITLE MODULE CODE
1 Introduction to JavaScript IS – OOP 223 – 1
JavaScript Programming :
2 IS – OOP 223 – 2
Fundamentals
3 JavaScript Control Structure IS – OOP 223 – 3
4 JavaScript Array Objects IS – OOP 223 – 4
JavaScript Methods, Classes and
5 IS – OOP 223 – 5
Object
6 JavaScript Advance Concepts IS – OOP 223 – 6
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
2 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
MODULE CONTENT
COURSE TITLE: Object-Oriented Programming (JavaScript)
MODULE TITLE: Java-Script Advance Concepts
NOMINAL DURATION: __8___ HRS
SPECIFIC LEARNING OBJECTIVES:
At the end of this module, you MUST be able to:
1. Discuss and Familiarized with JavaScript Error Handling, validations, and
animation.
2. Discuss and Familiarized with the HTML Document Object Model (DOM).
TOPIC: (SUB TOPIC)
1. JavaScript Advanced Concepts
Error Handling
Validations
Animation
HTML DOM
o Methods
o Documents
o Elements
o Forms
o CSS
ASSESSMENT METHOD/S:
Quiz, Oral Recitation, Peer Learning
REFERENCES:
[Link]
[Link]
[Link]
[Link]
[Link]
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
3 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Information Sheet
OOP Advance Concepts
Learning Objectives:
After reading this INFORMATION SHEET, YOU MUST be able to:
1. Discuss and Familiarized with JavaScript Error Handling, validations,
and animation.
2. Discuss and Familiarized with the HTML Document Object Model
(DOM).
JavaScript - Errors & Exceptions Handling
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime
Errors, and (c) Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a
closing parenthesis.
<script type = "text/javascript">
<!--
[Link](;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the
same thread as the syntax error is affected and the rest of the code in other
threads gets executed assuming nothing in them depends on the code
containing the error.
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
For example, the following line causes a runtime error because here the syntax
is correct, but at runtime, it is trying to call a method that does not exist.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
4 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
<script type = "text/javascript">
<!--
[Link]();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other
JavaScript threads to continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors
are not the result of a syntax or runtime error. Instead, they occur when you
make a mistake in the logic that drives your script and you do not get the
result you expected.
You cannot catch those errors, because it depends on your business
requirement what type of logic you want to put in your program.
The try...catch...finally Statement
The latest versions of JavaScript added exception handling capabilities.
JavaScript implements the try...catch...finally construct as well as
the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you
cannot catch JavaScript syntax errors.
Here is the try...catch...finally block syntax −
<script type = "text/javascript">
<!--
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
5 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or
one finally block (or one of both). When an exception occurs in the try block,
the exception is placed in e and the catch block is executed. The
optional finally block executes unconditionally after try/catch.
Examples
Here is an example where we are trying to call a non-existing function which in
turn is raising an exception. Let us see how it behaves without try...catch−
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
Try it yourself to SEE the result.
Now let us try to catch this exception using try...catch and display a user-
friendly message. You can also suppress this message, if you want to hide this
error from a user.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
6 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + [Link] );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
Try it yourself to SEE the result.
You can use finally block which will always execute unconditionally after the
try/catch. Here is an example.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
7 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + [Link] );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
Try it yourself to SEE the result.
The throw Statement
You can use throw statement to raise your built-in exceptions or your
customized exceptions. Later these exceptions can be captured and you can
take an appropriate action.
Example
The following example demonstrates how to use a throw statement.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
8 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
var a = 100;
var b = 0;
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
Try it yourself to SEE the result.
You can raise an exception in one function using a string, integer, Boolean, or
an object and then you can capture that exception either in the same function
as we did above, or in another function using a try...catch block.
The onerror() Method
The onerror event handler was the first feature to facilitate error handling in
JavaScript. The error event is fired on the window object whenever an
exception occurs on the page.
<html>
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
9 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
<head>
<script type = "text/javascript">
<!--
[Link] = function () {
alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
Try it yourself to SEE the result.
The onerror event handler provides three pieces of information to identify the
exact nature of the error −
Error message − The same message that the browser would display for
the given error
URL − The file in which the error occurred
Line number− The line number in the given URL that caused the error
Here is the example to show how to extract this information.
Example
<html>
<head>
<script type = "text/javascript">
<!--
[Link] = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
10 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
Try it yourself to SEE the result.
You can display extracted information in whatever way you think it is better.
You can use an onerror method, as shown below, to display an error message
in case there is any problem in loading an image.
<img src="[Link]" onerror="alert('An error occurred loading the image.')"
/>
You can use onerror with many HTML tags to display appropriate messages in
case of errors.
JavaScript - Form 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. This was really a lengthy process which used to put a
lot of burden on the server.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
11 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
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.
Example
We will take an example to understand the process of validation. Here is a
simple form in html format.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/[Link]" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
12 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Output
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
13 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Basic Form Validation
First let us see how to do a basic form validation. In the above form, we are
calling validate() to validate data when onsubmit event is occurring. The
following code shows the implementation of this validate() function.
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {
if( [Link] == "" ) {
alert( "Please provide your name!" );
[Link]() ;
return false;
}
if( [Link] == "" ) {
alert( "Please provide your Email!" );
[Link]() ;
return false;
}
if( [Link] == "" || isNaN(
[Link] ) ||
[Link] != 5 ) {
alert( "Please provide a zip in the format #####." );
[Link]() ;
return false;
}
if( [Link] == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Data Format Validation
Now we will see how we can validate our entered form data before submitting it
to the web server.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
14 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
The following example shows how to validate an entered email address. An
email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must
not be the first character of the email address, and the last dot must at least be
one character after the ‘@’ sign.
Example
Try the following code for email validation.
<script type = "text/javascript">
<!--
function validateEmail() {
var emailID = [Link];
atpos = [Link]("@");
dotpos = [Link](".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
[Link]() ;
return false;
}
return( true );
}
//-->
</script>
JavaScript - Animation
You can use JavaScript to create a complex animation having, but not limited
to, the following elements −
Fireworks
Fade Effect
Roll-in or Roll-out
Page-in or Page-out
Object movements
You might be interested in existing JavaScript based animation
library: [Link].
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
15 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
This tutorial provides a basic understanding of how to use JavaScript to create
an animation.
JavaScript can be used to move a number of DOM elements (<img />, <div> or
any other HTML element) around the page according to some sort of pattern
determined by a logical equation or function.
JavaScript provides the following two functions to be frequently used in
animation programs.
setTimeout( function, duration) − This function
calls function after duration milliseconds from now.
setInterval(function, duration) − This function calls function after
every duration milliseconds.
clearTimeout(setTimeout_variable) − This function calls clears any
timer set by the setTimeout() functions.
JavaScript can also set a number of attributes of a DOM object including its
position on the screen. You can set top and left attribute of an object to
position it anywhere on the screen. Here is its syntax.
// Set distance from left edge of the screen.
[Link] = distance in pixels or points;
or
// Set distance from top edge of the screen.
[Link] = distance in pixels or points;
Manual Animation
So let's implement one simple animation using DOM object properties and
JavaScript functions as follows. The following list contains different DOM
methods.
We are using the JavaScript function getElementById() to get a DOM
object and then assigning it to a global variable imgObj.
We have defined an initialization function init() to
initialize imgObj where we have set its position and left attributes.
We are calling initialization function at the time of window load.
Finally, we are calling moveRight() function to increase the left distance
by 10 pixels. You could also set it to a negative value to move it to the
left side.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
16 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Example
Try the following example.
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
var imgObj = null;
function init() {
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px';
}
function moveRight() {
[Link] = parseInt([Link]) + 10 + 'px';
}
[Link] = init;
//-->
</script>
</head>
<body>
<form>
<img id = "myImage" src = "/images/[Link]" />
<p>Click button below to move the image to right</p>
<input type = "button" value = "Click Me" onclick = "moveRight();" />
</form>
</body>
</html>
Output
Try it yourself to SEE the result.
Automated Animation
In the above example, we saw how an image moves to right with every click. We
can automate this process by using the JavaScript function setTimeout() as
follows −
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
17 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Here we have added more methods. So let's see what is new here −
The moveRight() function is calling setTimeout() function to set the
position of imgObj.
We have added a new function stop() to clear the timer set
by setTimeout() function and to set the object at its initial position.
Example
Try the following example code.
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
var imgObj = null;
var animate ;
function init() {
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px';
}
function moveRight() {
[Link] = parseInt([Link]) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop() {
clearTimeout(animate);
[Link] = '0px';
}
[Link] = init;
//-->
</script>
</head>
<body>
<form>
<img id = "myImage" src = "/images/[Link]" />
<p>Click the buttons below to handle animation</p>
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
18 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
<input type = "button" value = "Start" onclick = "moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body>
</html>
Output
Try it yourself to SEE the result.
Rollover with a Mouse Event
Here is a simple example showing image rollover with a mouse event.
Let's see what we are using in the following example −
At the time of loading this page, the ‘if’ statement checks for the
existence of the image object. If the image object is unavailable, this
block will not be executed.
The Image() constructor creates and preloads a new image object
called image1.
The src property is assigned the name of the external image file called
/images/[Link].
Similarly, we have created image2 object and assigned /images/[Link]
in this object.
The # (hash mark) disables the link so that the browser does not try to go
to a URL when clicked. This link is an image.
The onMouseOver event handler is triggered when the user's mouse
moves onto the link, and the onMouseOut event handler is triggered
when the user's mouse moves away from the link (image).
When the mouse moves over the image, the HTTP image changes from
the first image to the second one. When the mouse is moved away from
the image, the original image is displayed.
When the mouse is moved away from the link, the initial image [Link]
will reappear on the screen.
<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type = "text/javascript">
<!--
if([Link]) {
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
19 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
var image1 = new Image(); // Preload an image
[Link] = "/images/[Link]";
var image2 = new Image(); // Preload second image
[Link] = "/images/[Link]";
}
//-->
</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p>
<a href = "#" onMouseOver = "[Link] = [Link];"
onMouseOut = "[Link] = [Link];">
<img name = "myImage" src = "/images/[Link]" />
</a>
</body>
</html>
Output
Try it yourself to SEE the result.
JavaScript - Document Object Model or DOM
With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of
the page.
The HTML DOM model is constructed as a tree of Objects:
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
20 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
The HTML DOM Tree of Objects
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 You Will Learn
In the next chapters of this tutorial you will learn:
How to change the content of HTML elements
How to change the style (CSS) of HTML elements
How to react to HTML DOM events
How to add and delete HTML elements
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
21 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
The DOM defines a standard for accessing documents:
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
In other words: The HTML DOM is a standard for how to get, change, add,
or delete HTML elements.
JavaScript - HTML DOM Methods
HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or
change.
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 the properties and methods of each object.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
22 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
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).
Example
The following example changes the content (the innerHTML) of the <p> element
with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
Output
My First Page
Hello World!
In the example above, getElementById is a method, while innerHTML is
a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the
element.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
23 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
In the example above the getElementById method used id="demo" to find the
element.
The innerHTML Property
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.
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
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.
Below are some examples of how you can use the document object to access
and manipulate HTML.
Finding HTML Elements
Method Description
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
24 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
[Link](id) Find an element by element id
[Link](name) Find elements by tag name
[Link](name) Find elements by class name
Changing HTML Elements
Property Description
[Link] = new html content Change the inner HTML of an element
[Link] = new value Change the style of an HTML element
[Link] = new style
Method Description
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
25 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
[Link](attribute, value) Change the attribute value of an HTML
element
Adding and Deleting Elements
Method Description
[Link](element) Create an HTML element
[Link](element) Remove an HTML element
[Link](element) Add an HTML element
[Link](new, old) Replace an HTML element
[Link](text) Write into the HTML output stream
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
26 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Adding Events Handlers
Method Description
[Link](id).onclick = function(){code} Adding event handler code to a
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 D
O
M
[Link] Returns all <a> elements that have a name 1
attribute
[Link] Deprecated 1
[Link] Returns the absolute base URI of the document 3
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
27 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
[Link] Returns the <body> element 1
[Link] Returns the document's cookie 1
[Link] Returns the document's doctype 3
[Link] Returns the <html> element 3
[Link] Returns the mode used by the browser 3
[Link] Returns the URI of the document 3
[Link] Returns the domain name of the document 1
server
[Link] Obsolete. 3
[Link] Returns all <embed> elements 3
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
28 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
[Link] Returns all <form> elements 1
[Link] Returns the <head> element 3
[Link] Returns all <img> elements 1
[Link] Returns the DOM implementation 3
[Link] Returns the document's encoding (character set) 3
[Link] Returns the date and time the document was 3
updated
[Link] Returns all <area> and <a> elements that have a 1
href attribute
[Link] Returns the (loading) status of the document 3
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
29 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
[Link] Returns the URI of the referrer (the linking 1
document)
[Link] Returns all <script> elements 3
[Link] Returns if error checking is enforced 3
[Link] Returns the <title> element 1
[Link] Returns the complete URL of the document 1
JavaScript HTML DOM Elements
This page teaches you how to find and access HTML elements in an HTML
page.
Finding HTML Elements
Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are several ways to do this:
Finding HTML elements by id
Finding HTML elements by tag name
Finding HTML elements by class name
Finding HTML elements by CSS selectors
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
30 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Finding HTML elements by HTML object collections
Finding HTML Element by Id
The easiest way to find an HTML element in the DOM, is by using the element
id.
This example finds the element with id="intro":
Example
const element = [Link]("intro");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p id="intro">Finding HTML Elements by Id</p>
<p>This example demonstrates the <b>getElementsById</b> method.</p>
<p id="demo"></p>
<script>
const element = [Link]("intro");
[Link]("demo").innerHTML =
"The text from the intro paragraph is: " + [Link];
</script>
</body>
</html>
Output
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
31 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
JavaScript HTML DOM
Finding HTML Elements by Id
This example demonstrates the getElementsById method.
The text from the intro paragraph is: Finding HTML Elements by Id
If the element is found, the method will return the element as an object (in
element).
If the element is not found, element will contain null.
Finding HTML Elements by Tag Name
This example finds all <p> elements:
Example
const element = [Link]("p");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Tag Name.</p>
<p>This example demonstrates the <b>getElementsByTagName</b>
method.</p>
<p id="demo"></p>
<script>
const element = [Link]("p");
[Link]("demo").innerHTML = 'The text in first paragraph
(index 0) is: ' + element[0].innerHTML;
</script>
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
32 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
</body>
</html>
Output
JavaScript HTML DOM
Finding HTML Elements by Tag Name.
This example demonstrates the getElementsByTagName method.
The text in first paragraph (index 0) is: Finding HTML Elements by Tag Name.
This example finds the element with id="main", and then finds all <p> elements
inside "main":
Example
const x = [Link]("main");
const y = [Link]("p");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<div id="main">
<p>Finding HTML Elements by Tag Name</p>
<p>This example demonstrates the <b>getElementsByTagName</b>
method.</p>
</div>
<p id="demo"></p>
<script>
const x = [Link]("main");
const y = [Link]("p");
[Link]("demo").innerHTML =
'The first paragraph (index 0) inside "main" is: ' + y[0].innerHTML;
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
33 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
</script>
</body>
</html>
Output
JavaScript HTML DOM
Finding HTML Elements by Tag Name
This example demonstrates the getElementsByTagName method.
The first paragraph (index 0) inside "main" is: Finding HTML Elements by Tag
Name
Finding HTML Elements by Class Name
If you want to find all HTML elements with the same class name,
use getElementsByClassName().
This example returns a list of all elements with class="intro".
Example
const x = [Link]("intro");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Finding HTML Elements by Class Name.</p>
<p class="intro">Hello World!</p>
<p class="intro">This example demonstrates the
<b>getElementsByClassName</b> method.</p>
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
34 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
<p id="demo"></p>
<script>
const x = [Link]("intro");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>
</body>
</html>
Output
JavaScript HTML DOM
Finding HTML Elements by Class Name.
Hello World!
This example demonstrates the getElementsByClassName method.
The first paragraph (index 0) with class="intro" is: Hello World!
JavaScript Forms
JavaScript Form Validation
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns
false, to prevent the form from being submitted:
JavaScript Example
function validateForm() {
let x = [Link]["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
35 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
}
}
The function can be called when the form is submitted:
HTML Form Example
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = [Link]["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
36 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Output
Try it yourself to SEE the result.
JavaScript Can Validate Numeric Input
JavaScript is often used to validate numeric input:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = [Link]("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
[Link]("demo").innerHTML = text;
}
</script>
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
37 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
</body>
</html>
Output
Please input a number between 1 and 10
Submit
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:
HTML Form Example
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
38 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
</body>
</html>
Output
Try it yourself to SEE the result.
NOTE:
Automatic HTML form validation does not work in Internet Explorer 9 or
earlier.
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and
useful.
Typical validation tasks are:
has the user filled in all required fields?
has the user entered a valid date?
has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many
different ways.
Server side validation is performed by a web server, after input has been sent
to the server.
Client side validation is performed by a web browser, before input is sent to a
web server.
HTML Constraint Validation
HTML5 introduced a new HTML validation concept called constraint
validation.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
39 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
HTML constraint validation is based on:
Constraint validation HTML Input Attributes
Constraint validation CSS Pseudo Selectors
Constraint validation DOM Properties and Methods
Constraint Validation HTML Input Attributes
Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
type Specifies the type of an input element
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
40 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
For a full list, go to HTML Input Attributes.
Constraint Validation CSS Pseudo Selectors
Selector Description
:disabled Selects input elements with the "disabled" attribute specified
:invalid Selects input elements with invalid values
:optional Selects input elements with no "required" attribute specified
:required Selects input elements with the "required" attribute specified
:valid Selects input elements with valid values
JavaScript HTML DOM - Changing CSS
The HTML DOM allows JavaScript to change the style of HTML elements.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
41 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Changing HTML Style
To change the style of an HTML element, use this syntax:
[Link](id).[Link] = new style
The following example changes the style of a <p> element:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Changing the HTML style:</p>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
<script>
[Link]("p2").[Link] = "blue";
[Link]("p2").[Link] = "Arial";
[Link]("p2").[Link] = "larger";
</script>
</body>
</html>
Output
JavaScript HTML DOM
Changing the HTML style:
Hello World!
Hello World!
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
42 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02
Using Events
The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
An element is clicked on
The page has loaded
Input fields are changed
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id="id1", when the
user clicks a button:
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="[Link]('id1').[Link] = 'red'">
Click Me!</button>
</body>
</html>
Output
Try it yourself to SEE the result.
Bulacan Date Developed:
Polytechnic AY 2021 - 2022
43 of 43
BSIS / ACT Date Revised:
IS – OOP – 223 College January 12, 2023
Object-Oriented
Programming Developed by:
(JavaScript) Document No. Reynaldo P. Santos
Revision # 02