Week 9: DOM & Events
JS | DOM Manipulation, Events, classList, createElement
- الـ DOM والأحداث — شرح عملي — main.js: الوضع الداكن وقائمة الجوال وزر الأعلى، ثم workshops.js: البحث والتصفية وتفويض الأحداث، والتحقق من الاستمارة والحاسبة الفورية · 9 دقائق
Week 09 - DOM Manipulation & Events
Web Development 1 — Al-Aqsa University
What is the DOM?
The Document Object Model (DOM) is a programming interface for HTML documents. When the browser loads a web page, it creates a tree structure (like a family tree) of all the HTML elements. JavaScript can then read and modify this tree to change what's displayed on the page.
The DOM Tree
Every HTML element becomes a "node" in the tree. The <html> element is the root, <head> and <body> are children, and so on. Text inside elements becomes "text nodes."
// The document object is the entry point to the DOM
console.log(document); // The entire document
console.log(document.title); // Page title
console.log(document.URL); // Current URL
console.log(document.body); // The body element
console.log(document.head); // The head element
console.log(document.documentElement); // The html element
// Node relationships
const body = document.body;
console.log(body.parentNode); // html element
console.log(body.children); // HTMLCollection of child elements
console.log(body.firstElementChild); // First child element
console.log(body.lastElementChild); // Last child element
Selecting Elements
getElementById()
Returns a single element matching the given ID. Returns null if not found.
// HTML: <h1 id="title">Hello</h1>
const title = document.getElementById("title");
console.log(title); // <h1 id="title">Hello</h1>
console.log(title.textContent); // "Hello"
getElementsByClassName()
Returns a live HTMLCollection of all elements with the given class name.
// HTML: <p class="intro">First</p> <p class="intro">Second</p>
const intros = document.getElementsByClassName("intro");
console.log(intros.length); // 2
console.log(intros[0]); // First p element
// Loop through collection
for (let el of intros) {
console.log(el.textContent);
}
getElementsByTagName()
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length); // Number of p elements
querySelector() - Most Used!
Returns the first element matching any CSS selector. Returns null if not found.
// Select by ID
const title = document.querySelector("#title");
// Select by class
const firstIntro = document.querySelector(".intro");
// Select by tag
const firstP = document.querySelector("p");
// Complex selectors
const el = document.querySelector("div.card > h2");
const link = document.querySelector("a[href='#']");
const input = document.querySelector("input[type='email']");
const third = document.querySelector("li:nth-child(3)");
querySelectorAll()
Returns a static NodeList of ALL matching elements. Supports forEach directly.
const allCards = document.querySelectorAll(".card");
console.log(allCards.length);
// forEach works on NodeList
allCards.forEach((card, index) => {
console.log(`Card ${index}:`, card.textContent);
});
// Select multiple types
const headings = document.querySelectorAll("h1, h2, h3");
const btns = document.querySelectorAll("button[data-action]");
| Method |
Returns |
Collection Type |
CSS Selectors |
getElementById |
Single element |
- |
No (ID only) |
getElementsByClassName |
Multiple |
Live HTMLCollection |
No |
getElementsByTagName |
Multiple |
Live HTMLCollection |
No |
querySelector |
First match |
- |
Yes |
querySelectorAll |
All matches |
Static NodeList |
Yes |
Best Practice
Use querySelector and querySelectorAll in most cases. They are more flexible and support any CSS selector.
Modifying Content
// HTML: <div id="box"><p>Hello <strong>World</strong></p></div>
const box = document.querySelector("#box");
// innerHTML - gets/sets HTML content (parses HTML tags)
console.log(box.innerHTML);
// "<p>Hello <strong>World</strong></p>"
box.innerHTML = "<h2>New Content</h2><p>With HTML!</p>";
// Replaces everything inside the div
// textContent - gets/sets text only (ignores HTML tags)
console.log(box.textContent);
// "Hello World" (no HTML tags)
box.textContent = "Plain text <b>not bold</b>";
// Shows the literal text including "<b>" as visible text
// innerText - like textContent but respects CSS visibility
console.log(box.innerText);
// Similar to textContent but won't show hidden elements
Security Warning
Be careful with innerHTML when inserting user input! It can lead to XSS (Cross-Site Scripting) attacks. Use textContent for user-generated content.
Modifying Styles
Inline Styles (element.style)
const box = document.querySelector("#box");
// Set individual styles (camelCase!)
box.style.backgroundColor = "#ffc107";
box.style.color = "#000";
box.style.padding = "20px";
box.style.borderRadius = "10px"; // CSS: border-radius
box.style.fontSize = "1.2rem"; // CSS: font-size
box.style.display = "none"; // Hide element
box.style.display = "block"; // Show element
// Set multiple styles at once
box.style.cssText = "background: red; color: white; padding: 10px;";
// Read computed style (actual applied styles)
const styles = window.getComputedStyle(box);
console.log(styles.backgroundColor);
console.log(styles.width);
classList (Recommended!)
Better approach: define CSS classes and toggle them with JavaScript.
// CSS classes defined in stylesheet:
// .hidden { display: none; }
// .active { background: #ffc107; color: #000; }
// .shake { animation: shake 0.5s; }
const element = document.querySelector(".card");
// Add a class
element.classList.add("active");
element.classList.add("visible", "highlight"); // Multiple
// Remove a class
element.classList.remove("hidden");
// Toggle (add if absent, remove if present)
element.classList.toggle("active");
// Check if has class
if (element.classList.contains("active")) {
console.log("Element is active!");
}
// Replace a class
element.classList.replace("old-class", "new-class");
// Read all classes
console.log(element.className); // "card active visible"
console.log(element.classList); // DOMTokenList ["card", "active", "visible"]
Modifying Attributes
// HTML: <img id="photo" src="old.jpg" alt="Photo" data-user-id="42">
const img = document.querySelector("#photo");
// getAttribute - read any attribute
console.log(img.getAttribute("src")); // "old.jpg"
console.log(img.getAttribute("alt")); // "Photo"
// setAttribute - set/change any attribute
img.setAttribute("src", "new.jpg");
img.setAttribute("alt", "New Photo");
img.setAttribute("width", "200");
// removeAttribute
img.removeAttribute("width");
// hasAttribute
console.log(img.hasAttribute("alt")); // true
// Direct property access (for standard attributes)
console.log(img.src); // Full URL
console.log(img.alt); // "New Photo"
console.log(img.id); // "photo"
img.src = "another.jpg"; // Also works
// data-* attributes (custom data)
// HTML: <div data-user-id="42" data-role="admin">
const div = document.querySelector("div");
console.log(div.dataset.userId); // "42" (camelCase!)
console.log(div.dataset.role); // "admin"
div.dataset.status = "active"; // Creates data-status="active"
Creating and Adding Elements
// 1. Create the element
const newDiv = document.createElement("div");
// 2. Add content and attributes
newDiv.textContent = "I'm a new div!";
newDiv.className = "card";
newDiv.id = "newCard";
newDiv.style.background = "#1a1a2e";
// 3. Add to the page
document.body.appendChild(newDiv); // Add as last child of body
// ---- More ways to add elements ----
const container = document.querySelector("#container");
const newItem = document.createElement("p");
newItem.textContent = "New paragraph";
// appendChild - add as LAST child
container.appendChild(newItem);
// prepend - add as FIRST child
container.prepend(newItem);
// append - like appendChild but accepts strings too
container.append(newItem, "Some text");
// before/after - add as sibling
const reference = document.querySelector("#existing");
reference.before(newItem); // Insert before reference
reference.after(newItem); // Insert after reference
// insertBefore - insert before a specific child
container.insertBefore(newItem, reference);
// ---- Practical example: Build a list ----
const ul = document.createElement("ul");
const fruits = ["Apple", "Banana", "Cherry"];
fruits.forEach(fruit => {
const li = document.createElement("li");
li.textContent = fruit;
ul.appendChild(li);
});
document.body.appendChild(ul);
// ---- Creating complex elements with innerHTML ----
const card = document.createElement("div");
card.className = "card";
card.innerHTML = `
<h3>Card Title</h3>
<p>Card description goes here.</p>
<button class="btn">Learn More</button>
`;
container.appendChild(card);
Removing Elements
// Modern way: element.remove()
const item = document.querySelector(".item");
item.remove(); // Gone!
// Older way: parent.removeChild(child)
const parent = document.querySelector("#list");
const child = parent.querySelector("li:first-child");
parent.removeChild(child);
// Remove all children
container.innerHTML = ""; // Quick but destroys event listeners
// Better: remove children one by one
while (container.firstChild) {
container.removeChild(container.firstChild);
}
Cloning Elements
const original = document.querySelector(".card");
// Shallow clone (element only, no children)
const shallowClone = original.cloneNode(false);
// Deep clone (element + all children)
const deepClone = original.cloneNode(true);
deepClone.id = "card-clone"; // Change ID to avoid duplicates
document.body.appendChild(deepClone);
Events Introduction
Events are actions that happen in the browser: a user clicks a button, hovers over an element, types in a field, the page finishes loading, etc. JavaScript can "listen" for these events and run code in response.
addEventListener (Recommended)
const btn = document.querySelector("#myBtn");
// Add event listener
btn.addEventListener("click", function() {
console.log("Button clicked!");
});
// With arrow function
btn.addEventListener("click", () => {
console.log("Clicked again!");
});
// Named function (needed for removal)
function handleClick() {
console.log("Handled!");
}
btn.addEventListener("click", handleClick);
// Remove event listener (must use same function reference)
btn.removeEventListener("click", handleClick);
// One-time listener
btn.addEventListener("click", () => {
console.log("This runs only once!");
}, { once: true });
Avoid Inline Event Handlers
Don't use onclick="doSomething()" in HTML. Always use addEventListener in JavaScript for better separation of concerns and the ability to add multiple listeners.
Event Types
| Category | Event | Fires When |
| Mouse | click | Element is clicked |
dblclick | Element is double-clicked |
mouseenter | Mouse enters element (no bubbling) |
mouseleave | Mouse leaves element (no bubbling) |
mouseover | Mouse enters element or children (bubbles) |
mouseout | Mouse leaves element or children (bubbles) |
mousedown / mouseup | Mouse button pressed / released |
| Keyboard | keydown | Key is pressed down |
keyup | Key is released |
keypress | Key is pressed (deprecated) |
| Form | input | Input value changes (real-time) |
change | Input value changes (on blur) |
submit | Form is submitted |
| Focus | focus | Element receives focus |
blur | Element loses focus |
| Window | scroll | Page or element is scrolled |
resize | Window is resized |
load | Page/resource finished loading |
| Document | DOMContentLoaded | HTML parsed (before images load) |
// Mouse events
const box = document.querySelector(".box");
box.addEventListener("mouseenter", () => {
box.style.background = "#ffc107";
});
box.addEventListener("mouseleave", () => {
box.style.background = "#1a1a2e";
});
// Keyboard events
document.addEventListener("keydown", (e) => {
console.log("Key:", e.key); // "a", "Enter", "Escape"
console.log("Code:", e.code); // "KeyA", "Enter", "Escape"
});
// Form/Input events
const input = document.querySelector("input");
input.addEventListener("input", (e) => {
console.log("Typing:", e.target.value); // Real-time updates
});
input.addEventListener("focus", () => {
input.style.borderColor = "#ffc107";
});
input.addEventListener("blur", () => {
input.style.borderColor = "#333";
});
// Form submit
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault(); // Prevent page reload!
console.log("Form submitted!");
});
// Window events
window.addEventListener("scroll", () => {
console.log("Scroll Y:", window.scrollY);
});
window.addEventListener("resize", () => {
console.log("Width:", window.innerWidth);
});
// DOMContentLoaded - runs when HTML is ready
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM is ready!");
});
The Event Object
Every event handler receives an event object as its first argument. It contains useful information about the event:
const btn = document.querySelector("button");
btn.addEventListener("click", function(event) {
// (often abbreviated as 'e')
console.log(event.type); // "click"
console.log(event.target); // The element that triggered the event
console.log(event.currentTarget); // The element the listener is on
console.log(event.timeStamp); // When the event occurred
// Mouse position
console.log(event.clientX, event.clientY); // Relative to viewport
console.log(event.pageX, event.pageY); // Relative to page
// Prevent default browser behavior
event.preventDefault(); // e.g., prevent link navigation, form submit
// Stop propagation (bubbling)
event.stopPropagation(); // Don't let event bubble to parent
});
// target vs currentTarget example
// HTML: <div id="parent"><button>Click</button></div>
const parent = document.querySelector("#parent");
parent.addEventListener("click", (e) => {
console.log(e.target); // button (what was actually clicked)
console.log(e.currentTarget); // #parent (where listener is attached)
});
Event Bubbling and Capturing
When an event happens on an element, it first runs the handlers on it, then on its parent, then on its parent's parent, and so on up to document. This is called bubbling.
// HTML:
// <div id="grandparent">
// <div id="parent">
// <button id="child">Click Me</button>
// </div>
// </div>
document.querySelector("#grandparent").addEventListener("click", () => {
console.log("Grandparent clicked");
});
document.querySelector("#parent").addEventListener("click", () => {
console.log("Parent clicked");
});
document.querySelector("#child").addEventListener("click", () => {
console.log("Child clicked");
});
// Clicking the button logs:
// "Child clicked" (1st - target)
// "Parent clicked" (2nd - bubbles up)
// "Grandparent clicked" (3rd - bubbles up more)
// Stop bubbling
document.querySelector("#child").addEventListener("click", (e) => {
e.stopPropagation(); // Parent and grandparent won't fire
console.log("Only child fires");
});
// Capturing phase (rare, runs top-down before bubbling)
document.querySelector("#grandparent").addEventListener("click", () => {
console.log("Grandparent CAPTURE");
}, true); // third argument = useCapture
Event Delegation
Instead of adding event listeners to every child element, add ONE listener to the parent and use event.target to determine which child was clicked. This is more efficient and works with dynamically added elements.
// BAD: Adding listener to every item
const items = document.querySelectorAll("li");
items.forEach(item => {
item.addEventListener("click", () => {
console.log(item.textContent);
});
});
// Problem: new items added later won't have listeners!
// GOOD: Event delegation on parent
const list = document.querySelector("ul");
list.addEventListener("click", (e) => {
// Check if an <li> was clicked
if (e.target.tagName === "LI") {
console.log(e.target.textContent);
}
});
// Works even for items added later!
// Practical: Todo list with delete buttons
const todoList = document.querySelector("#todoList");
todoList.addEventListener("click", (e) => {
// Check if a delete button was clicked
if (e.target.classList.contains("delete-btn")) {
const li = e.target.closest("li"); // Find parent li
li.remove();
}
// Check if a checkbox was clicked
if (e.target.type === "checkbox") {
const li = e.target.closest("li");
li.classList.toggle("completed");
}
});
// Using closest() for more flexible matching
document.addEventListener("click", (e) => {
const card = e.target.closest(".card");
if (card) {
console.log("Clicked on card:", card.dataset.id);
}
});
Why Event Delegation?
- Performance: one listener instead of many
- Works with dynamically created elements
- Less memory usage
- Cleaner code
Complete Example: Interactive List
// Complete working example combining everything
const input = document.querySelector("#todoInput");
const addBtn = document.querySelector("#addBtn");
const list = document.querySelector("#list");
// Add new item
addBtn.addEventListener("click", () => {
const text = input.value.trim();
if (!text) return;
// Create elements
const li = document.createElement("li");
li.innerHTML = `
<input type="checkbox">
<span>${text}</span>
<button class="delete-btn">Delete</button>
`;
// Add to list
list.appendChild(li);
input.value = "";
input.focus();
});
// Event delegation for all list interactions
list.addEventListener("click", (e) => {
if (e.target.classList.contains("delete-btn")) {
e.target.closest("li").remove();
}
if (e.target.type === "checkbox") {
e.target.closest("li").classList.toggle("completed");
}
});
Summary
The DOM is your bridge between JavaScript and the web page. With element selection, modification, creation, and events, you can build fully interactive web applications. Practice with the To-Do List and Color Picker tasks!
Al-Aqsa University — Web Development 1