Web Programming IIUnit 710 min read
JavaScript Basics & DOM Manipulation: Syntax, Events, and Dynamic Web Content
Unit 7 of Web Programming II introduces JavaScript’s core syntax, event handling, and DOM manipulation to dynamically update web pages, enabling interactive user experiences without page reloads.
TAKEAWAYS:
- JavaScript is a client-side scripting language embedded in HTML to add interactivity, validate forms, and manipulate content dynamically.
- The DOM (Document Object Model) represents HTML elements as a tree structure, allowing JavaScript to modify styles, attributes, and content.
- Event listeners (e.g.,
onclick,onload) trigger JavaScript functions when user actions occur, enabling real-time responses. - Arrays and loops in JavaScript simplify data handling, while DOM methods like
getElementById()orquerySelector()target specific elements. - Security best practices (e.g., sanitizing inputs) are critical to prevent XSS attacks when manipulating DOM content.
- Real-world applications include eSewa’s transaction validation, Pathao’s ride-booking UI, and Khalti’s payment form interactivity.
1. Introduction to JavaScript
JavaScript (JS) is a lightweight, interpreted scripting language used to make web pages dynamic and interactive. Unlike HTML (structure) or CSS (styling), JavaScript adds behavior—e.g., form validation, animations, or real-time updates.
1.1 Key Features of JavaScript
mindmap
root((JavaScript Features))
clientSide((Client-Side Execution))
dynamic((Dynamic Typing))
eventDriven((Event-Driven))
crossPlatform((Cross-Platform))
prototypal((Prototypal Inheritance))
**Note:** Add a brief description of each feature (e.g., "Runs in browser without server") as a tooltip or inline text.1.2 JavaScript Syntax Basics
JavaScript code is written inside <script> tags in HTML or external .js files.
Example: Hello World
<script>
alert("Hello, World!"); // Prints a popup
</script>
Variables and Data Types
JavaScript uses let, const, and var to declare variables.
let age = 25; // Number
const name = "Alice"; // String (immutable)
var isStudent = true; // Boolean
Operators
2. JavaScript Arrays
Arrays store multiple values in a single variable. Unlike Python, JavaScript arrays are dynamic (can hold mixed types).
2.1 Array Declaration
// Methods to create arrays
let fruits = ["Apple", "Banana", "Cherry"]; // Literal
let numbers = new Array(1, 2, 3); // Constructor
2.2 Array Methods
| Method | Description | Example |
|---|---|---|
push() |
Adds to end | fruits.push("Orange") |
pop() |
Removes from end | fruits.pop() |
shift() |
Removes from start | fruits.shift() |
unshift() |
Adds to start | fruits.unshift("Mango") |
slice() |
Extracts a portion | fruits.slice(1, 3) → ["Banana"] |
map() |
Transforms each element | numbers.map(x => x * 2) |
Worked Example: Sum of Array Elements
let nums = [10, 20, 30];
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
}
console.log(sum); // Output: 60
3. DOM (Document Object Model)
The DOM is a tree-like structure representing HTML elements, allowing JavaScript to modify them dynamically.
3.1 DOM Tree Representation
<html>
<head>...</head>
<body>
<div id="header">Title</div>
<ul id="menu">
<li>Home</li>
<li>About</li>
</ul>
</body>
</html>
Visualization:
html
/ \
head body
/ \
div ul
/ / \
"Title" li li
| |
"Home" "About"
3.2 Accessing DOM Elements
| Method | Description | Example |
|---|---|---|
getElementById() |
Gets element by ID | document.getElementById("menu") |
getElementsByClassName() |
Gets all elements by class | document.getElementsByClassName("btn") |
querySelector() |
Gets first matching CSS selector | document.querySelector(".active") |
querySelectorAll() |
Gets all matching CSS selectors | document.querySelectorAll("li") |
Example: Change Text Color
document.getElementById("header").style.color = "blue";
4. Event Handling
Events are user-triggered actions (e.g., clicks, keypresses) that execute JavaScript functions.
4.1 Common Events
| Event | Description | Example |
|---|---|---|
onclick |
Mouse click | <button onclick="alert('Clicked!')"> |
onload |
Page fully loaded | window.onload = function() {...} |
onchange |
Input field value changed | <input onchange="validate(this)"> |
keydown |
Key pressed | document.addEventListener("keydown", keyPressHandler); |
4.2 Adding Event Listeners
// Method 1: Inline HTML
<button onclick="myFunction()">Click Me</button>
// Method 2: JavaScript
let button = document.getElementById("myBtn");
button.addEventListener("click", function() {
alert("Button clicked!");
});
Worked Example: Validate a Number
function checkMultipleOf5() {
let num = parseInt(prompt("Enter a number:"));
if (num % 5 === 0) {
alert(num + " is a multiple of 5!");
} else {
alert(num + " is NOT a multiple of 5.");
}
}
Trace Table:
| Step | Action | Output |
|---|---|---|
| 1 | User inputs 20 |
num = 20 |
| 2 | 20 % 5 === 0 → true |
alert("20 is a multiple of 5!") |
5. DOM Manipulation Techniques
JavaScript can modify, create, or delete DOM elements.
5.1 Changing Content
document.getElementById("demo").innerHTML = "<b>New Text</b>";
5.2 Adding Elements
let newLi = document.createElement("li");
newLi.textContent = "New Item";
document.getElementById("menu").appendChild(newLi);
5.3 Removing Elements
let item = document.querySelector(".remove-me");
item.remove();
Example: Dynamic To-Do List
sequenceDiagram participant User participant DOM participant JS User->>JS: Clicks "Add Task" JS->>DOM: Creates new <li> JS->>DOM: Appends to <ul> DOM-->>User: Updates UI
6. Real-World Applications
In the Real World
eSewa’s Transaction Validation
- Idea: JavaScript validates user input (e.g., phone number format) before submitting to the server.
- How: Uses
onblurevent listeners to check fields dynamically. - Example: If a user enters
+9779841234567(correct format), eSewa’s JS confirms it matches^\+9779\d{8}$before proceeding.
Pathao’s Ride-Booking UI
- Idea: JavaScript updates the map in real-time as users drag the pickup/drop pins.
- How: Uses
mousemoveevents to recalculate distances and display estimated fares. - Example: When a user moves the drop pin near Thapathali, Pathao’s JS calls an API to fetch updated fare data and updates the UI without refreshing.
Khalti’s Payment Form
- Idea: JavaScript sanitizes inputs to prevent XSS attacks (e.g., stripping
<script>tags from user-entered card details). - How: Uses
textContentinstead ofinnerHTMLand escapes special characters. - Example: If a user accidentally pastes
<script>alert('hack')</script>into the card field, Khalti’s JS escapes it to<script>alert('hack')</script>, rendering it harmless.
- Idea: JavaScript sanitizes inputs to prevent XSS attacks (e.g., stripping
7. Security Considerations
JavaScript can expose vulnerabilities if not handled carefully:
- XSS (Cross-Site Scripting): Malicious scripts injected into web pages.
- Mitigation: Sanitize inputs (
textContentvs.innerHTML).
- Mitigation: Sanitize inputs (
- CSRF (Cross-Site Request Forgery): Tricks users into submitting unauthorized requests.
- Mitigation: Use CSRF tokens in forms.
- Data Leakage: Avoid logging sensitive data (e.g., passwords) to console.
Example: Safe DOM Update
// UNSAFE: Allows script injection
document.getElementById("output").innerHTML = userInput;
// SAFE: Escapes HTML
document.getElementById("output").textContent = userInput;
8. Exam Tips
- Syntax Overload: Memorize
let/const/var, array methods (push,map), and DOM selectors (getElementById,querySelector). - Event Handling: Know
onclick,onload, andaddEventListenersyntax. - DOM Manipulation: Practice changing content, adding/removing elements, and styling dynamically.
- Worked Examples: Expect questions like:
- "Write JS to check if a number is even/odd."
- "How would you add a new row to a table dynamically?"
- Security: Always mention sanitization or XSS prevention in DOM manipulation answers.
- Real-World Tie: Relate concepts to apps like eSewa (input validation) or Pathao (real-time UI updates).
Past Exam Question Practice:
- Define an array in JavaScript and list 3 methods.
let colors = ["Red", "Green", "Blue"]; // Methods: push(), pop(), slice() - Write JS to check if a number is a multiple of 5.
function isMultipleOf5(num) { return num % 5 === 0; } console.log(isMultipleOf5(15)); // true - Explain
getElementsByClassName()with an example.// Gets all elements with class "btn" let buttons = document.getElementsByClassName("btn"); for (let btn of buttons) { btn.style.background = "blue"; }
Based on the TU BITM syllabus for Web Programming II (IT219), unit 7.
Discussion
Loading…