Module-2
Module-2
CS380
Document Object Model
2
(DOM)
<html>
<head>
<title>JavaScript DOM</title>
</head>
<body>
<h1>Hello DOM!</h1>
</body>
</html>
CS380
Document Object Model
3
(DOM)
Document Object Model
4
(DOM)
It is a structure of HTML elements which
are converted to objects(nodes)
All these objects are arranged in tree
data Structure
HTML page loading( html elements --
objects)
This tree structure we call it as DOM
CS380
Document Object Model
5
(DOM)
Features of DOM
1. Accessing HTML Elements
2. Modifying Content Dynamically
CS380
Document Object Model
6
(DOM)
Why DOM is created.
Using JS we can manipulate HTML
document so that we can provide
dynamic user content
DOM manipulation
How to access any DOM node(html
element)
How to add new html elements
let element =
document.getElementById("demo");
element.style.color = "blue";
</script>
CS380
Access HTML Elements in
8
JavaScript
2. Accessing by Class Name
Selects multiple elements with the same class.
Returns an HTMLCollection (array-like object).
Can loop through elements to apply changes.
<p class="myClass">Paragraph 1</p>
<p class="myClass">Paragraph 2</p>
<script>
let elements =
document.getElementsByClassName("myClass");
for (let i = 0; i < elements.length; i++) {
elements[i].style.color = "green";
}
</script>
CS380
Access HTML Elements in
9
JavaScript
3. Accessing by Tag Name
Selects all elements of a specific tag.
Returns an HTMLCollection.
Useful for bulk modifications.
<p>First Paragraph</p>
<p>Second Paragraph</p>
<script>
let elements = document.getElementsByTagName("p");
for (let i = 0; i < elements.length; i++) {
elements[i].style.fontSize = "20px";
}
</script>
CS380
Access HTML Elements in
10
JavaScript
4. Accessing by Query Selector (First
Match)
Selects the first element that matches the given
CSS selector.
Returns a single element.
More flexible than getElementById.
<script>
let element =
document.querySelector(".myClass");
CS380
element.style.fontWeight = "bold";
Access HTML Elements in
11
JavaScript
5. Accessing by Query Selector (All Matches)
Selects all elements matching a CSS selector.
Returns a NodeList (similar to an array).
Can use forEach to iterate over elements.
<p class="myClass">First Paragraph</p>
<p class="myClass">Second Paragraph</p>
<script>
let elements = document.querySelectorAll(".myClass");
elements.forEach(element => {
element.style.backgroundColor = "yellow";
});
</script>
CS380
Selecting Elements by
12
Attribute Name
1. Selecting Elements by Attribute
Name (hasAttribute())
✔ Use getElementsByTagName() to get all
elements of a specific tag.
✔ Loop through the elements and use
hasAttribute("attribute-name") to check if
the attribute exists.
✔ Useful when you need to find an element
with a specific attribute but without
knowing its value.
CS380
Selecting Elements by
13
Attribute Name
2. Selecting Elements by Attribute
Value (getAttribute())
✔ Use getElementsByTagName() to get all
elements.
✔ Use getAttribute("attribute-name") to
compare an attribute's value.
✔ Stops at the first match (using break) to
improve efficiency.
✔ Useful when you need to find an element
with a specific attribute value.
CS380
Selecting Elements by
14
Attribute Name
3. Selecting Elements by Partial
Attribute Value (includes())
✔ Use getAttribute("attribute-name") and
check if it contains a specific keyword.
✔ includes("value") helps filter attributes
dynamically.
✔ Useful when attribute values are dynamic
or partially match a keyword.
✔ Stops after finding the first match for
performance optimization.
CS380
Traversing the DOM
15
CS380
Traversing the DOM
16
CS380
Traversing the DOM
17
CS380
Traversing the DOM
18
CS380
Traversing the DOM
19
CS380
Accessing and Updating
20
text
Accessing and Updating Using
nodeValue,
innerText, and
innerHTML
CS380
Accessing and Updating
21
text
Accessing and Updating Using
nodeValue,
innerText, and
innerHTML
CS380
1. nodeValue
22
CS380
23
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello, World!</p>
<button onclick="changeNodeValue()">Click Me</button>
<script>
function changeNodeValue() {
document.getElementById("demo").firstChild.nodeValue =
"Welcome ISE";
}
</script>
</body>
</html>
CS380
2. innerText
24
CS380
25
<!DOCTYPE html>
<html>
<body>
<script>
function changeInnerText() {
document.getElementById("demo").innerText = "Welcome
ISE";
}
</script>
CS380
</body>
3. innerHTML
26
CS380
27
<!DOCTYPE html>
<html>
<body>
<p id="demo">Hello, World!</p>
<button onclick="changeInnerHTML()">Click Me</button>
<script>
function changeInnerHTML() {
document.getElementById("demo").innerHTML =
"<b>Welcome ISE</b>";
}
</script>
</body>
</html>
CS380
Adding HTML Elements
28
DOM Manipulations
createElement()
createTextNode()
appendChild()
innerHTML
CS380
Using DOM Manipulations
29
1. Using document.createElement()
✔ Creates a new HTML element
dynamically.
✔ Uses appendChild() to add it to the
document.
✔ Useful for adding elements based on
user actions.
CS380
30
2.Using createTextNode()
✔ Uses createTextNode() to create a text
node separately and append it to <p>.
CS380
<!DOCTYPE html>
<html>
31 <body>
<p>Hello, World!</p>
<button onclick="addElement()">Click Me</button>
<script>
function addElement() {
let newPara = document.createElement("p");
let textNode =
document.createTextNode("Welcome ISE"); // Create
text node
newPara.appendChild(textNode); // Append text
to <p>
document.body.appendChild(newPara); // Append
<p> to body
}
CS380
</script>
32
<!DOCTYPE html>
<html>
<body>
<p>Hello, World!</p>
<button onclick="addElement()">Click Me</button>
<script>
function addElement() {
let newPara = document.createElement("p");
newPara.innerHTML = "Welcome ISE";
document.body.appendChild(newPara); // Append to
body
}
</script>
</body>
CS380
33
Using insertBefore()
✔ Inserts a new element before an
existing one.
✔ Requires a reference node and its
parent node.
CS380
<!DOCTYPE html>
<html>
34
<body>
<script>
function insertElement() {
let newPara = document.createElement("p");
newPara.innerHTML = "Welcome ISE";
let parent = document.body;
let existingPara =
document.getElementById("existing");
parent.insertBefore(newPara, existingPara);
CS380 }
</script>
Using innerHTML
35
CS380
36
<!DOCTYPE html>
<html>
<body>
<script>
function addUsingInnerHTML() {
document.body.innerHTML += "<p>Welcome
ISE</p>";
CS380 }
</script>
Removing HTML Elements
37
CS380
38
1. Using removeChild()
✔ Removes a specific child element from
its parent.
✔ Requires both the parent element and
the child element.
CS380
39
<!DOCTYPE html>
<html>
<body>
<p id="para">Hello, World!</p>
<button onclick="removeElement()">Click Me</button>
<script>
function removeElement() {
let parent = document.body;
let child = document.getElementById("para");
parent.removeChild(child); // Remove the <p> element
}
</script>
</body>
CS380
</html>
40
CS380
41
<!DOCTYPE html>
<html>
<body>
<p id="para">Hello, World!</p>
<button onclick="removeElement()">Click Me</button>
<script>
function removeElement() {
document.getElementById("para").remove(); //
Directly remove <p>
}
</script>
</body>
</html>
CS380
42
CS380
43
<!DOCTYPE html>
<html>
<body>
<p>Hello, World!</p>
<p>Welcome to ISE</p>
<button onclick="clearBody()">Click Me</button>
<script>
function clearBody() {
document.body.innerHTML = ""; // Clears entire body
content
}
</script>
</body>
</html>
CS380
Adding and Removing
44
Attributes Using JavaScript
✔ Use setAttribute() to add/modify
attributes.
✔ Use removeAttribute() to remove
attributes.
CS380
Adding Attributes
45
CS380
46
<!DOCTYPE html>
<html>
<body>
<button id="btn" onclick="addAttribute()">Click
Me</button>
<script>
function addAttribute() {
let btn = document.getElementById("btn");
btn.setAttribute("disabled", "true"); // Adds
'disabled' attribute
}
</script>
</body>
CS380
</html>
Removing an Attribute
47
<!DOCTYPE html>
<html>
<body>
<button id="btn" disabled
onclick="removeAttribute()">Click Me</button>
<script>
function removeAttribute() {
let btn = document.getElementById("btn");
btn.removeAttribute("disabled"); // Removes
'disabled' attribute
}
</script>
</body>
CS380
</html>
Updating HTML Content
48
Using document.write()
✔ document.write() replaces the entire
<!DOCTYPE html>
<html>
<body>
<p>Hello, World!</p>
<button onclick="updateContent()">Click Me</button>
<script>
function updateContent() {
document.write("Welcome ISE"); // Overwrites
everything
}
</script>
</body>
</html>
CS380
document.write() While
50
Loading
This does not erase existing content since it's called during
page load.
<!DOCTYPE html>
<html>
<body>
<script>
document.write("<p>Welcome ISE</p>"); // Adds a
new paragraph
</script>
</body>
</html>
✅ This works safely because document.write() is used while
the page is being loaded.
CS380
51
CS380
Events in JavaScript
52
CS380
2️⃣Common Event Types
54
CS380
Events
55
CS380
Events
56
CS380
Events
57
CS380
Events
58
CS380
Events
59
CS380
HOW EVENTS TRIGGER JS
60
CODE
When the user interacts with the HTML
on a web page,
there are three steps involved in getting
it to trigger some JavaScript code.
Together these steps are known as
event handling.
CS380
HOW EVENTS TRIGGER JS
61
CODE
1️⃣Selecting Elements
✔ Identify the HTML element(s) to respond
to (e.g., link, button, form).
✔ Use DOM queries like getElementById(),
getElementsByClassName(), etc.
✔ Browser-specific events (e.g., page load,
scroll) work with the window object.
CS380
HOW EVENTS TRIGGER JS
62
CODE
2️⃣Binding Events
✔ Specify which event should trigger the
code (e.g., click, mouseover, submit).
✔ Attach events to DOM nodes (elements).
✔ Some events work with all elements
(e.g., mouseover), while others are
element-specific (e.g., submit for forms).
CS380
HOW EVENTS TRIGGER JS
63
CODE
3️⃣Defining Event Handlers
✔ Provide the code (function) to run when
the event occurs.
✔ Can be a named function or an
anonymous function.
✔ Example: Changing text when a button is
clicked.
CS380
HOW EVENTS TRIGGER JS
64
CODE
<!DOCTYPE html>
<html>
<body>
<p id="text">Hello, World!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("text").innerHTML = "Welcome
ISE";
}
</script>
</body>
</html>
CS380
3 Ways to Bind an Event to an
Element
65
CS380
3 Ways to Bind an Event to an
Element
66
CS380
3 Ways to Bind an Event to an
Element
67
CS380
3 Ways to Bind an Event to an
Element
68
document.getElementById("btn").on
click = function() {
document.getElementById("text").innerH
TML = "Welcome ISE";
CS380 };
3 Ways to Bind an Event to an
Element
69
CS380
3 Ways to Bind an Event to an
Element
70
document.getElementById("btn").addEventListener("click
", function() {
document.getElementById("text").innerHTML =
"Welcome ISE";
});
document.getElementById("btn").addEventListener("click
CS380
", function() {
Event Listeners
71
element.addEventListener(event, function,
EventFlow);
event: Type of event to listen for (e.g.,
"click", "mouseover").
function: The code to run when the
event occurs.
EventFlow (optional): Boolean
indicating if event capturing is used.
Defaults to false (bubbling).
CS380
Event Listeners
73
<html>
<body>
<p id="text">Hello, World!</p>
<button id="btn">Click Me</button>
<script>
let btn = document.getElementById("btn");
let text = document.getElementById("text");
// Adding first event listener to change text
btn.addEventListener("click", function() { text.innerHTML =
"Welcome ISE"; });
// Adding second event listener to show an alert
btn.addEventListener("click", function() { alert("Button
Clicked!"); });
CS380 </script>
</body>
Using Parameters with Event
74
Listeners
Using Parameters with Event Listeners
Event listeners can pass parameters to
functions by using an anonymous
function or arrow function.
Directly calling a function with
parameters in addEventListener()
doesn't work, so a wrapper function is
needed.
CS380
✅ Example: Passing Parameters
75
<html>
<body>
<p id="text">Hello, World!</p>
<button id="btn">Click Me</button>
<script>
function changeText(message) {
document.getElementById("text").innerHTML = message;
}
document.getElementById("btn").addEventListener("click",
function() {
changeText("Welcome ISE");
});
</script>
</body>
</html>
CS380
Direct Function Call Doesn't
76
Work:
btn.addEventListener("click",
changeText("Welcome ISE")); // ❌ Doesn't
work
Use a Wrapper Function:
Wrap the function call inside an anonymous
or arrow function to pass arguments.
Preferred for Dynamic Data:
Useful when the event listener needs to
work with dynamic data or multiple
parameters.
CS380
Event Object
77
CS380
Event---- actions
80
CS380
Bind an Event to an Element
81
CS380
✅ Event Bubbling
82
Example Scenario:
If you click a button inside a <div>, the
CS380
✅ Explanation:
83
itself)
Div Clicked! (Event Bubbling) (Triggered
the div.
JavaScript executes the click event
CS380
<!DOCTYPE html>
<html>
<body>
84
<div id="parent" style="padding: 20px; background-color: lightblue;">
<button id="child">Click Me</button>
</div>
<script>
// Event listener for the child (button)
document.getElementById("child").addEventListener("click", function() {
alert("Button Clicked!");
});
document.getElementById("child").addEventL
istener("click", function(event) {
event.stopPropagation();
alert("Button Clicked!");
});
Now, only "Button Clicked!" will appear.
CS380
Event bubbling and
86
caputring
CS380
✅ Event Capturing (Trickling
87
Phase)
Event Capturing (also called trickling) is
the opposite of Event Bubbling.
The event starts from the outermost
element (parent) and moves inward to
the target element (child).
CS380
<!DOCTYPE html>
<html>
<body>
88
<div id="parent" style="padding: 20px; background-color:
lightblue;">
<button id="child">Click Me</button>
</div>
<script>
// Parent element listener (Capturing Phase)
document.getElementById("parent").addEventListener("click",
function() {
alert("Div Clicked! (Event Capturing)");
}, true); // 'true' enables capturing
document.getElementById("child").addEventListener("click",
function() {
alert("Button Clicked!");
});
</script>
CS380
</body>
✅ Event Delegation
89
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<script>
let buttons = document.querySelectorAll("button");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
alert("Button Clicked!");
});
}
</script>
CS380
<html>
<body>
91
<div id="bookshelf">
<div class="book">Book 1</div>
<div class="book">Book 2</div>
<div class="book">Book 3</div>
</div>
<script>
// Adding a single event listener to the bookshelf (parent)
document.getElementById("bookshelf").addEventListener("click",
function(event) {
if (event.target.classList.contains("book")) {
alert("You picked up: " + event.target.textContent);
CS380 }
USER INTERFACE EVENTS
92
📌 Explanation
load Event - Alerts when the page fully
loads.
unload Event - Logs a message when
the user leaves the page.
scroll Event - Logs messages while
scrolling the page.
resize Event - Logs a message when
resizing the browser window.
CS380
example
93
<html>
<body style="height: 2000px;">
<h1>JavaScript Event Handling Example</h1>
<script>
// 1. 'load' Event
window.addEventListener('load', function() {
alert('Page is fully loaded!'); // Triggered when the
page finishes loading
});
// 2. 'unload' Event
window.addEventListener('unload', function() {
console.log('You are leaving the page.'); //
Triggered when the user leaves the page
CS380
});
94
// 3. 'scroll' Event
window.addEventListener('scroll', function() {
console.log('You are scrolling the page.'); // Triggered when the user
scrolls the page
});
// 4. 'resize' Event
window.addEventListener('resize', function() {
console.log('Window size changed!'); // Triggered when the window
is resized
});
</script>
</body>
</html>
CS380
✅ Focus & Blur Events
95
Example
<html>
<body>
<h1>Focus & Blur Events Example</h1>
<input type="text" id="nameInput" placeholder="Enter your name">
<script>
const inputField = document.getElementById("nameInput");
CS380
96
CS380
✅ Mouse Events
97
CS380
✅ Form Events
99
state.
focus - Triggered when an element (like an input)
gains focus.
blur - Triggered when an element (like an input)
loses focus.
change - Triggered when the value of an input,
CS380
Types of Validation
10
1
Client-side Validation: Handled using
JavaScript before sending data to the
server.
Server-side Validation: Handled on
Email).
Pattern matching using Regular
Email Validation
Checks for valid email format.
<input type="email" name="email" required>
Number Validation
Allows only numbers within a specified range.
<input type="number" name="age" min="1" max="100"
required>
Pattern
CS380 Matching
✅ HTML5 Form Validations
10
5
Ensures minimum character length.
<input type="password" name="password" minlength="6"
required>
URL Validation
Validates proper URL format.
<input type="url" name="website" required>
Date Validation
Allows only date input.
<input type="date" name="dob" required>
Range Slider
CS380
✅ HTML5 Form Validations
10
6
Select a value from a specified range.
<input type="range" name="volume" min="0" max="100"
required>
Color Picker
Allows user to select a color.
<input type="color" name="favcolor" required>
CS380