JavaScript
JavaScript
Language Fundamentals
8/22/2025
Client Side Scripting
CS380 2
Why use client-side
programming?
Server scripting languages(PHP) already allows us to
create dynamic web pages. Why also use client-side
scripting?
• client-side scripting (JavaScript) benefits:
• usability: can modify a page without having to post back
to the server (faster UI)
• efficiency: can make small, quick changes to page
without waiting for server
• event-driven: can respond to user actions like clicks and
key presses
CS380 3
Server-side programming?
• server-side programming (PHP) benefits:
• security: has access to server's private data; client can't
see source code
• compatibility: not subject to browser compatibility
issues
• power: can write files, open connections to servers,
connect to databases, ...
CS380 4
About JavaScript
• JavaScript is not Java, or even related to Java
• The original name for JavaScript was “LiveScript”
• The name was changed when Java became popular
• Statements in JavaScript resemble statements in Java,
because both languages borrowed heavily from the C
language
• JavaScript should be fairly easy for Java programmers to learn
• However, JavaScript is a complete, full-featured, complex language
• JavaScript is seldom used to write complete “programs”
• Instead, small bits of JavaScript are used to add functionality to
HTML pages
• JavaScript is often used in conjunction with HTML “forms”
• JavaScript is reasonably platform-independent
Javascript everywhere
• Popular programming language
• Can be used in any application in any platform
• Web Application, Mobile Application Machine learning
etc
• JS Engine is available in most of the browsers
10/25/2025
Hello world program
Execute ?
10/25/2025
Execution
• In browser console (without html and css) – JS engine
• Inside html JS engine
• Command prompt (without browser)
• Need node js (can run javascript on OS)
• Runtime environment
• Download
• Check node - - version
• To run- node f1.js
• To quit – CTRLC twice
10/25/2025
Variables – let
• let data = 10 create a variable using let
• let name = “XYZ”
• Constants
• Const data=100
• What is var ?
10/25/2025
var
• Variables declared with the var keyword can NOT
have block scope.
• Variables declared inside a { } block can be
accessed from outside the block.
• Redeclaring a variable using the var keyword can
impose problems.
• Redeclaring a variable inside a block will also
redeclare the variable outside the block:
10/25/2025
• Redeclaring a variable using the let keyword can
solve this problem.
10/25/2025
Egs (redeclaration and scope)
let x = 0; var x = 0;
• var x = 10;
// Here x is 10
• let x = 10;
// Here x is 10
{
{ var x = 2;
let x = 2; // Here x is 2
// Here x is 2 }
}
// Here x is 2
// Here x is 10
10/25/2025
let x=10 var x=10
{ {
let x="hello" var x="hello"
console.log(x) console.log(x)
} }
console.log(x) Console.log(x)
10/25/2025
Data Types
• Primitive – Number(float), String, Boolean, Null,
Undefined, Symbol
• Object – not a primitive type
10/25/2025
Number
• typeof X
• Underscores for long numbers(instead of comma)
• Infinity, -infinity
• MAX_VALUE
• Bigint – add n at the end of the number
• Let x= bigint(123232323423552)
• let x = 9999999999999999;
let y = 9999999999999999n;
10/25/2025
Strings
• Single quote, double quote
• Escape sequences
• Let s= ‘Sdnfksdnfjksndk \‘sscdfbsdhbfsbfd’
10/25/2025
boolean
• True
• False
10/25/2025
undefined,Empty
• undefined – undefined datatype
let car;
console.log(car)
Empty
let car = "";
console.log(car)
console.log(typeof car)
10/25/2025
Type Conversion
• Convert one datatype to another
• Explicit Conversion
• Let x= number(“100”)
10/25/2025
• Converting Strings to Numbers
• Converting Numbers to Strings
• Converting Dates to Numbers
• Converting Numbers to Dates
• Converting Booleans to Numbers
• Converting Numbers to Booleans
10/25/2025
Converting Strings to
Numbers
• The global method Number() converts a variable (or a value) into a
number.
10/25/2025
• Converting Dates to Strings
• console.log(String(Date()))
• Output: Mon Aug 19 2024 14:44:35
GMT+0530 (India Standard Time)
10/25/2025
10/25/2025
• Converting Booleans to Numbers
• The global method Number() can also convert
booleans to numbers.
let x= Number(false) // returns 0
let y=Number(true)
console.log(x)
console.log(y)
10/25/2025
• Converting Booleans to Strings
• The global method String() can convert booleans to
strings.
10/25/2025
Automatic Type
Conversion
• When JavaScript tries to operate on a "wrong" data
type, it will try to convert the value to a "right" type.
10/25/2025
Type Coercion
• Operating with two different datatypes
• Decide the operation
• 2 +” sample” -> string operation
• 2- sample -> number operation
• Any type to Boolean
• truthy values- all values are converted as true
• except undefined, null, Nan, 0, “ “, false – falsy values
• true + true =?
• Let x = Boolean(“”)
10/25/2025
Operators
• Arithmetic Operators - +, -, *, /, %, **
• Shorthand operators +=, -= …
• preincrement
• postincrement
• Eg n=5
• x= n++ x=5, n=6
• n = ++x x=6 n=6
• Value of n and x after the above statements?
10/25/2025
Operators - Arithmetic
• Arithmetic Operators - +, -, *, /, %
• Shorthand operators +=, -= …
• preincrement
• postincrement
• Eg n=5
• x= n++
• n = ++x
• Value of n and x after the above statements?
• x= 6 n=6
10/25/2025
Relational Operators
• <, >, <=, >=, ==, ===(data and type)
• Output is a Boolean value
• Compare
• number and number
• String and string
• String and number
10/25/2025
Other operators
• Logical operators:
&& || ! (&& and || are short-circuit operators)
• Bitwise operators:
& | ^ ~ << >> >>>
• Assignment operators:
+= -= *= /= %= <<= >>= >>>= &=
^= |=
• String operator:
+
• The conditional operator:
condition ? value_if_true : value_if_false
• Additional operators:
new typeof void delete
10/25/2025
Comments
• Comments are as in C or Java:
• Between // and the end of the line
• Between /* and */
• Java’s javadoc comments, /** ... */, are treated just
the same as /* ... */ comments; they have no special
meaning in JavaScript
for loop (same as Java)-
output?
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
var s1 = "hello";
JS
var s2 = "";
for (var i = 0; i < s1.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
CS380 34
for loop (same as Java)
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
var s1 = "hello";
JS
var s2 = "";
for (var i = 0; i < s1.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
CS380 35
while loops (same as Java)
while (condition) {
statements;
}
do {
statements;
} while (condition);
break and continue keywords also behave as
in Java
CS380 36
Array – different ways to
create an array
• You can use an array literal:
var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty
array:
– var colors = new Array();
• You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue";
colors[1]="green";
• You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
• You can use new Array(…) with two or more
arguments to create an array containing those
values:
Arrays
var name = []; // empty array
var name = [value, value, ..., value]; //
pre-filled
name[index]
var ducks = = value; //
["Huey", store element
"Dewey", "Louie"];
var stooges = []; // stooges.length is 0
JS
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
CS380 38
Array methods
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
array serves as many data structures: list, queue, stack, ...
methods: concat, join, pop, push, reverse, shift, slice, sort,
splice, toString, unshift
push and pop add/remove from back
unshift and shift add/remove from front
shift and pop return the element that is removed
slice returns a piece of the array but it doesn’t affect the
original array. splice changes the original array by removing,
replacing, or adding values and returns the affected values. 39
String type
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" "));
// "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
10/25/2025
More about String
escape sequences behave as in Java: \' \" \& \
n \t \\
converting between numbers and Strings:
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN
10/25/2025
1.Write a JavaScript program that accepts a number as input
and inserts dashes (-) between each even and odd number
combination.
For example, if you accept 025478 the output should be 02-
54-78.
10/25/2025
• npm install prompt-sync
10/25/2025
Addition of 2 numbers
const prompt = require("prompt-sync")();
10/25/2025
JAVASCRIPT programs
10/25/2025
JavaScript Classes are
templates for JavaScript
Objects.
10/25/2025
this is a special keyword in JavaScript that refers to the object that is
currently using the code.
10/25/2025
10/25/2025
class Car {
constructor(name, year) { //Initializing object
this.name = name; property
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
console.log(myCar1.name)
10/25/2025
10/25/2025
Class methods program
class Person{
constructor(name,year)
{
this.name=name;
this.year=year;
}
age(){
const date = new Date();
return date.getFullYear() - this.year;
}
}
const car=new Person('glanza',2024)
console.log("My car is " + car.age() + " years old.");
10/25/2025
Objects – not primitive
ones
• To represent real-world entity in the virtual world.
• let student = { } // empty object
• let student = {
key1 : value1,
key2: value2 } //like dictionary
}
const person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"};
• Access all or particular property
• Student or student.key1 or
student[‘key1’]
10/25/2025
Objects(Other way of
creating an object)
const car={name:"glanza",year:2024};
const car1={name:"kiger",year:2022};
console.log(car.name)
console.log("I purchased my second
car in the year",car1.year)
10/25/2025
Arrays and objects
• Arrays are objects – special objects
• In JavaScript, objects use named
indexes whereas Arrays use
numbered indexes.
• car = { myCar: "Saturn", 7: "Mazda" }
– car[7] is the same as car.7
– car.myCar is the same as car["myCar"]
• If you know the name of a property, you
can use dot notation: car.myCar
• If you don’t know the name of a
property, but you have it in a variable
(or can compute it), you must use array
• console.log(student.name)
• console.log(student[‘name’]);
• prop1= ‘name’
• console.log(student[prop1]) // cannot use dot
operator if it is variable
• Add functions
10/25/2025
Complex objects
• Object within an object
• let boxOfStuff = {
book: "Object-Oriented JavaScript",
smallerBox:
{ stuff: ["pencils", "pens"],
smallestBox: { stuff: ["paper clips",
"thumbtacks"] }
}
};
console.log(boxOfStuff.smallerBox.smallestBox.st
uff)
10/25/2025
• console.log(boxOfStuff.smallerBox.smalle
stBox.stuff);
// Output: ["paper clips", "thumbtacks"]
If paperclips to be accessed?
10/25/2025
• console.log(boxOfStuff.smallerBox.smallestBox.stuff);
// Output: ["paper clips", "thumbtacks"]
If paperclips to be accessed?
console.log(boxOfStuff.smallerBox.smallestBox.stuff[0]
);
Or
console.log(boxOfStuff['smallerBox']['smallestBox']
['stuff'][0]);
// Output: "paper clips"
10/25/2025
Complex Objects
• Examples( with function, variable)
– car = {myCar: "Saturn", 7: "Mazda",
getCar: CarTypes("Honda"), special: Sales}
• The fields are myCar, getCar, 7 (this is a legal
field name) , and special
• "Saturn" and "Mazda" are Strings
• CarTypes is a function call
• Sales is a variable you defined earlier
• Example use: document.write("I own a " +
car.myCar);
Three ways to create an
object
• You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
• You can use new to create a “blank” object, and
add fields to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
• You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave");
• Write a javascript program to print key names in
javascript objects
10/25/2025
• console.log(Object.keys(Course));
• Object.values(Course) ?
10/25/2025
The for…in statement to
Iterate on object’s properties
• You can loop through all the properties of an object with
‘for’ (variable in object) statement;
• Example: for (var prop in course) {
console.log(prop + ": " + course[prop]);
}
• for (let key in student)
{ console.log(key, student[key]) // not dot
operator
10/25/2025
const person = {fname:"John", lname:"Doe",
age:25};
10/25/2025
const numbers = [45, 4, 9, 16, 25];
10/25/2025
The with statement
The with keyword is used as a kind of shorthand for referencing
an object's properties or methods.
The object specified as an argument to ‘with’ becomes the default
object for the duration of the block that follows.
The properties and methods for the object can be used
without naming the object.
Syntax
The syntax for “with” object is as follows −
with (object){
properties used without the object name and dot
}
10/25/2025
eg
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
10/25/2025
Now use html command to include
the javascript output in html
• Use alert
or
• document.write("<h1>Hello World!</h1>") ;
or
• Document.getelementbyID(“
id”).innerHTML =Course[0]
10/25/2025
Functions
• Reuse the set of statements
• Dividing the tasks into small tasks.
• function message()
{console.log(“Welcome”); }
message()
message()
10/25/2025
User input in nodejs
10/25/2025
Compare 2 no’s(Run-time input)
const readline = require("readline-sync");
function max(x,y)
{ if (x>y)
return x;
else
return y;
}
let x1 = Number(readline.question("Enter x value:"));
let y1 = Number(readline.question("enter y value:"));
10/25/2025
More about Functions
• Functions are objects with method called “( )”
• A property of an object may be a function (=method)
• function max(x,y) { if (x>y) return x; else return y;};
• max.description = “return the maximum of two arguments”;
• Local declarations may appear in function body
• Call can supply any number of arguments
• functionname.length : # of arguments in definition
• functionname.arguments.length : # arguments in call
• Basic types are passed by value, objects by reference
• “Anonymous” functions
• (function (x,y) {return x+y}) (2,3);
slide 77
Anonymous functions:In JavaScript, an
anonymous function is a function
without a name.
10/25/2025
Arrow functions
let add = function(x,y)
{return x+y;}
let sum = add(2,3)
let result = sum(4,5);
10/25/2025
Arrow functions
let add =(x,y) => {return x+y;}
let sum = add(2,3)
Console.log(sum)
It uses the => syntax and is often used for anonymous functions.
10/25/2025
Arrow functions
let add = (x,y) => return x+y; // no need for braces if only one statement
10/25/2025
Functions with parameters
• function message(name)
{ console.log(“Welcome”+name);}
message(“XYZ”);
• function message(name)
{ return(“Welcome”+name)}
Msg = message(“XYZ”);
console.log(Msg)
10/25/2025
Objects with functions
• const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + "
" + this.lastName;
}
};
slide 84
.
class ClassName {
constructor() { ... } // add attributes
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
10/25/2025
example
object Class
class Person {
constructor(name, age) {
let person = { this.name = name;
this.age = age;
name: 'John',
}
age: 30,
sayHello: function() { sayHello() {
console.log(`Hello, my name is $
console.log('Hello, my {this.name} and I'm ${this.age} years old.`);
name is ' + this.name + I’m }
+ this.age + ); }
} const john = new Person('John', 30);
john.sayHello();
};
10/25/2025
• Objects can also be created using the
Object.create() method. This method can
be very useful, because it allows you to
choose the prototype object for the
object you want to create, without having
to define a constructor function.
10/25/2025
Classes Vs Objects in JS
• Use a class when:
1.You need to create multiple objects with the same structure
and behavior.
2.You want to use inheritance to create a class hierarchy and
reuse code.
3.You want to use polymorphism to treat objects of different
classes as if they were the same type.
4.You want to encapsulate data and behavior in a single unit.
• Use an object when:
1.You need a single entity with specific state and behavior.
2.You don’t need to create multiple objects with the same
structure and behavior.
3.You don’t need to use inheritance or polymorphism.
4.You want a simple way to store and manipulate data.
10/25/2025
Try it
•Define a class named Account with a constructor that initializes properties such as accountNumber, accountHolder, and balance.
•Include methods within the class:
•displayAccountInfo: Display the account details (account number, account holder, balance).
•deposit: Accept an amount and add it to the account balance.
•withdraw: Accept an amount and subtract it from the account balance, ensuring sufficient funds.
• Create two instances of the Account class, representing different bank accounts.
• Call the displayAccountInfo method for each account to show their initial details.
• Perform a deposit operation on one account and a withdrawal operation on the others
• Call the displayAccountInfo method again for each account to show their updated details.
Your JavaScript program should demonstrate the use of classes, objects, and functions to model a basic banking system. Make
sure to handle scenarios where there might be insufficient funds during a withdrawal.
10/25/2025
Javascript in webpages
10/25/2025
Web page request
10/25/2025
Client Side Validation
• Done when the user input is validated by the
browser before it is sent to the server,
• Using HTML attributes, JavaScript, or other
scripting languages.
• Advantages
• provides instant feedback to the user
without reloading the page,
• reducing server load and bandwidth, and
• improving the user interface and usability.
• Drawbacks-
• bypassed by disabling or manipulating the browser
settings or scripts,
• being inconsistent across different browsers,
devices, and platforms, and being complex and
time-consuming to implement and maintain.
10/25/2025
Server Side Validation
• Is when the user input is validated by the server after it is
received from the browser, using languages such as PHP or
ASP.
• Provides a more reliable and secure validation, as it
can prevent malicious or invalid data from entering
the database or affecting the server functionality.
• Provides a more consistent and compatible validation,
as it can handle different browsers, devices, and
platforms, and apply the same rules and logic.
• provides a more flexible and dynamic validation, as it
can access the database or other resources, and
perform more complex or conditional validations.
• However, server-side validation can also cause a delay or lag
in the user feedback, increase the server load and
bandwidth, and degrade the user interface and usability.
10/25/2025
When and where to use
• Combining client-side and server-side validation is
the best practice for form validation, as it provides a
balance between the advantages and disadvantages of
each technique.
• Generally, client-side validation should be used for basic
and simple validations, such as required fields, format,
and range,
• while server-side validation should be used for advanced
and complex validations, such as uniqueness, existence,
and logic.
• Additionally, client-side validation can provide immediate
and interactive feedback to the user, and improve the
user experience and interface, while server-side
validation can provide final and authoritative validation,
and ensure data integrity and security.
• By following these guidelines, you can create a more
effective and efficient form validation for your data entry
10/25/2025
tasks.
Using JavaScript in html
document
• JavaScript code is included within <script> tags:
– <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
• Notes:
• The type attribute is to allow you to use other
scripting languages (but JavaScript is the default)
• This simple code does the same thing as just putting
<h1>Hello World!</h1> in the same place in the
HTML document
• The semicolon at the end of the JavaScript statement
is optional
• You need semicolons if you put two or more statements
on the same line
• It’s probably a good idea to keep using semicolons
Where to put JavaScript
• JavaScript can be put in the <head> or in the <body>
of an HTML document
• JavaScript functions should be defined in the <head>
• This ensures that the function is loaded before it is
needed
• JavaScript in the <body> will be executed as the page
loads
• JavaScript can be put in a separate .js file
– <script src="myJavaScriptFile.js"></script>
• Put this HTML wherever you would put the actual
JavaScript code
• An external .js file lets you use the same JavaScript on
multiple HTML pages
• The external .js file cannot itself contain a <script> tag
• JavaScript can be put in HTML form object, such
How to set up client side validation
10/25/2025
Using HTML for client-side
validation
• Making fields required using “required”
• Constraining the length of data:
• minlength, maxlength: for text data
• min and max for the min and max value of num type
• Restricting the type of data using type:
• <input type="email" name="multiple>
• Specifying data patterns using pattern:
• specifies a regex pattern that the entered form data
needs to match
10/25/2025
HTML- validation
<form>
<label for="firstname"> First Name: </label>
<input type="text" name="firstname" id="firstname" required
maxlength="45">
<label for="lastname"> Last Name: </label>
<input type="text" name="lastname" id="lastname" required
maxlength="45">
<button>Submit</button>
</form>
10/25/2025
Using Regexp for
validation
• A regular expression (regexp) is a pattern
that can be used to match character
combinations in text strings, so regexps are
ideal for form validation and serve a variety
of other uses in JavaScript.
10/25/2025
A simple example using reg expr
<html lang="en">
<head>
CS380 103
An example for validation
using javascript
function validateUsername() {
var username = document.getElementById("username").value;
var usernameError = document.getElementById("usernameError");
if (username.trim() === "") {
usernameError.textContent = "Username cannot be empty.";
}
else {
for (var i = 0; i < username.length; i++)
{ var char = username[i];
if (!((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >=
'0' && char <= '9’)))
{ usernameError.textContent = "Invalid character in the username. Use
only letters and numbers."; return;
}
}
10/25/2025
Javascript Assignment 5.1, 5.2, 5.3 – Check the ppt for clear details
• Modify the JS welcome() function to check fname to have the first letter as a Capital letter followed by small case letters(No numbers or
other characters)followed by a space and capital letter and then small case letters
• Use .js file to write the welcome function.
• Try the same with pattern matching in html
• You are going to create an input form using HTML5 and Javascript. This input form will not submit any database to the server (you learn to
do this in COP4834). It will validate and collect information from the user and go to a confirm page that displays the information entered
and allows the user to confirm that the information is correct. Below are all the input form fields and the validation required.
• It is up to you (the designer) how you present the information request. For example in entering a date you can have a single text box, or you
can have multiple boxes with drop down choices. You do, however, have to validate the data to make sure it meets all validation rules.
• Once the user enters all this information in the form and hits submit, you will present the information and allow the user to confirm that it is
all correct. The user should not be able to enter invalid data or leave fields blank.
• The form will be sent to your email address using the form action=”mailto:address”
• Add a password field and Add a password strength bar to check the strength of your password.
• strong password : includes atleast 1 lowercase alphabet, atleast 1 uppercase alphabet, atleast one digit, atleast 1 special
character except dot and atleast 8 characters long. And not the username itself.
• medium password: same as above but no digits and can be atleast 6 characters long
• Weak password: If the password entered does not meet the strong or medium-level requirements,
then it is deemed weak.
10/25/2025
Assignment 5.2
• You are going to create an input form using HTML5 and Javascript. This input form will not submit any database to the server (you learn to
do this in COP4834). It will validate and collect information from the user and go to a confirm page that displays the information entered
and allows the user to confirm that the information is correct. Below are all the input form fields and the validation required.
• It is up to you (the designer) how you present the information request. For example in entering a date you can have a single text box, or you
can have multiple boxes with drop down choices. You do, however, have to validate the data to make sure it meets all validation rules.
• Once the user enters all this information in the form and hits submit, you will present the information and allow the user to confirm that it is
all correct. The user should not be able to enter invalid data or leave fields blank.
• The form will be sent to your email address using the form action=”mailto:address ”
10/25/2025
Assignment 5.2 --contd
(Use Javascript function)
• Add a password field and Add a password strength bar
to check the strength of your password.
• strong password : includes atleast 1 lowercase alphabet,
atleast 1 uppercase alphabet, atleast one digit, atleast 1
special character except dot and atleast 8 characters
long. And not the username itself.
• medium password: same as above but no digits and can
be atleast 6 characters long
• Weak password: If the password entered does
not meet the strong or medium-level
requirements, then it is deemed weak.
10/25/2025
How does Javascript
understand HTML document ?
• When an HTML document is loaded in the browser
– another representation of the same document is
generated as shown:
• Htmldoc JS view – DOM tree
10/25/2025
• HTML cannot be manipulated directly.
• It can be done using DOM with the help of Javascript
• 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.
10/25/2025
DOM
Manipulations
10/25/2025
Navigation between the
nodes
•nodeValue- innerHTML
•nodeName-
•parentNode
•childNodes[nodenumber]
•firstChild – childNodes[0]
•lastChild
•nextSibling
•previousSibling
Eg.
document.getElementById(“p1").firstChild.nodeValue;
document.getElementById(“p1").firstChild.nodeName;
10/25/2025
Javascript for 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
10/25/2025
Methods for manipulations
document object represents the web page.
• Finding HTML Element by Id
• const element=document.getElementById(“id1")
• Finding HTML Element by Tag Name
• const element=document.getElementsByTagName("p");
• Finding HTML Elements by Class Name
• const x=document.getElementsByClassName("intro");
• Finding HTML Elements by CSS Selectors
• const x = document.querySelectorAll("p.intro");
• returns a list of all <p> elements with class="intro
10/25/2025
Changing attributes…
Property Description
element.innerHTML = new html Change the inner HTML of an
content element
element.attribute = new value Change the attribute value of an
HTML element
element.style.property = new style Change the style of an HTML
element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an
HTML element
10/25/2025
Element Manipulation
10/25/2025
Finding HTML Objects
• document.anchors
• document.body
• document.documentElement
• document.embeds
• document.forms
• document.head
• document.images
• document.links
• document.scripts
• document.title
10/25/2025
Simple example
<html lang="en">
<head>
<title>Simple example of JS in
html</title>
</head> Change the text
<body> to “Welcome”
using JS
( dynamically)
<p id="sample">HELLO WORLD!!!
</p>
</body>
</html>
10/25/2025
Modify the example
<html lang="en">
<head>
<title>Simple example of JS in html</title>
</head> Display the
<body> URL of the
<script> document
document.getElementById("sample").innerHTML="WEL
COME !!!";
</script>
<p id="sample">HELLO WORLD!!! </p>
</body>
</html>
10/25/2025
Contd..
<body>
<p id="sample">HELLO WORLD!!! </p>
<script>
document.getElementById("sample").innerH
TML=document.URL;
</script>
</body>
10/25/2025
Assignment 5.3
• Identify the different ways of displaying the scripts
available in the document and show in the next page
of the document.
• Identify the number of HTML elements in the web
document
• Identify the number of each type of HTML element
in the document
10/25/2025
DOM Events
<form name="f1"
onsubmit="welcome(document.getElementById('fname').value)">
<label for="fname"> Name:</label>
<input type= "text" id = fname pattern="[A-Za-z]+" title="start
with caps" required/>