DOM Manipulation & Web Interactivity (Selecting, Modifying, Events & Dynamic Lists)
Welcome to Phase 11: DOM Manipulation! DOM (Document Object Model) webpage structure ni JavaScript interact cheyagalige in-memory tree representation ga provide chesthundhi. HTML document browser lo load avvagane, browser static HTML tags ni JavaScript Objects ga convert chesi Node Tree Hierarchy ni construct chesthundhi. In this comprehensive masterclass guide, you will master element selectors (getElementById, querySelector, querySelectorAll), changing text, HTML, styles and classes (classList), reading form inputs, dynamic element creation (createElement, append, remove), data attributes (dataset), DOM traversal (parentElement, closest), dynamic list rendering, and build 4 interactive browser UI projects.
Browser HTML document ni parse chesi memory lo create chese hierarchical tree structure ni DOM (Document Object Model) antaru. Dheenilo prati HTML tag, attribute, text oka Node Object ga untundhi. JavaScript ee DOM nodes ni access chesi webpage content, layout, mariyu styles ni dynamically live ga update cheyyagaladhu:
โโโ document (Document Object)
โโโ <html>
โโโ <head> (title, meta, links)
โโโ <body>
โโโ <h1 id="title">Old Title</h1>
โโโ <button id="changeButton">Change Title</button>
| Method | Selector Syntax | Return Type | Description |
|---|---|---|---|
document.getElementById('id') |
Only ID string: 'title' |
Single Element or null |
Fastest selector by unique ID. |
document.querySelector('css') โญ Recommended |
CSS Selector: '#title', '.btn', 'div > p' |
FIRST matching Element or null |
Modern universal selector for any CSS query. |
document.querySelectorAll('css') |
CSS Selector: '.item' |
Static NodeList (all matches) |
Returns collection of all matches. Supports .forEach(). |
<!-- HTML Structure -->
<h1 id="title">Old Title</h1>
<button id="changeButton">Change Title</button>
<script>
// Select elements
const title = document.querySelector("#title");
const button = document.querySelector("#changeButton");
// Attach click event listener
button.addEventListener("click", () => {
title.textContent = "New Title";
title.style.color = "#10b981";
});
</script>
Element lopali raw plain text ni update chesthundi. HTML tags ni text gane treat chesthundi, preventing XSS (Cross-Site Scripting) attacks!
HTML tags ni parse chesi render chesthundi (e.g. <strong>Bold</strong>). User input ni direct ga innerHTML lo inject cheyyakudadhu!
"use strict";
const box = document.querySelector("#box");
// 1. Safe plain text
box.textContent = "Welcome to JavaScript 2026!";
// 2. Rich HTML Rendering
box.innerHTML = "<span style='color: #10b981;'>Welcome</span> to <strong>Our Compiler</strong>!";
Inline styles rayadam badhulu CSS classes ni classList API tho manage cheyyadam best industry practice:
element.classList.add("active", "highlight")โ Adds classes.element.classList.remove("hidden")โ Removes class.element.classList.toggle("dark-mode")โ Adds if missing, removes if present (perfect for theme switchers!).element.classList.contains("active")โ Returns booleantrue/false.
"use strict";
const card = document.querySelector(".card");
// Toggle card expansion
card.classList.toggle("expanded");
if (card.classList.contains("expanded")) {
console.log("Card is currently open!");
}
| Method | Description | Example |
|---|---|---|
document.createElement(tag) | Creates new unattached DOM element node | const div = document.createElement('div'); |
parent.append(...nodes) | Inserts nodes/text at END of parent (ES6 โญ) | list.append(newLi); |
parent.prepend(...nodes) | Inserts nodes at START of parent | list.prepend(newLi); |
element.remove() | Removes the element directly from DOM tree | item.remove(); |
"use strict";
const container = document.querySelector("#list-container");
// 1. Create element
const newCard = document.createElement("div");
newCard.className = "item-card";
newCard.textContent = "New Dynamic Module";
// 2. Set dataset attribute
newCard.dataset.moduleId = "mod_42";
// 3. Append to parent
container.append(newCard);
// 4. Delete after 5 seconds
// newCard.remove();
- Data Attributes (
data-*): Custom metadata stored on HTML tags:<button data-user-id="101" data-action="delete">$ ightarrow$ read withbutton.dataset.userIdandbutton.dataset.action. - DOM Traversal:
el.parentElementโ Immediate parent element.el.childrenโ Direct child elements.el.closest('.target-selector')โญ โ Traverses UPwards from current element to find closest matching ancestor (ideal for event delegation!).
Mastering DOM manipulation through 4 complete production components:
Project 1: Dynamic Task Manager (Create, Toggle, Delete)
<!-- HTML -->
<input type="text" id="taskInput" placeholder="Enter new task...">
<button id="addTaskBtn">Add Task</button>
<ul id="taskList"></ul>
<script>
const taskInput = document.querySelector("#taskInput");
const addTaskBtn = document.querySelector("#addTaskBtn");
const taskList = document.querySelector("#taskList");
addTaskBtn.addEventListener("click", () => {
const text = taskInput.value.trim();
if (!text) return alert("Please enter task name!");
// 1. Create LI element
const li = document.createElement("li");
li.textContent = text;
li.style.cursor = "pointer";
// 2. Create Delete button
const delBtn = document.createElement("button");
delBtn.textContent = " โ";
delBtn.style.marginLeft = "10px";
// Toggle complete
li.addEventListener("click", (e) => {
if (e.target !== delBtn) li.style.textDecoration = li.style.textDecoration === "line-through" ? "none" : "line-through";
});
// Delete item
delBtn.addEventListener("click", () => li.remove());
li.append(delBtn);
taskList.append(li);
taskInput.value = ""; // Clear input
});
</script>
Project 2: Dark/Light Mode Switcher with classList.toggle
const themeToggleBtn = document.querySelector("#themeToggle");
themeToggleBtn.addEventListener("click", () => {
document.body.classList.toggle("light-theme");
const isLight = document.body.classList.contains("light-theme");
themeToggleBtn.textContent = isLight ? "๐ Dark Mode" : "โ๏ธ Light Mode";
localStorage.setItem("user-theme", isLight ? "light" : "dark");
});
Project 3: Live Character & Word Counter for Textarea
const textarea = document.querySelector("#editor");
const charCountDisplay = document.querySelector("#charCount");
const wordCountDisplay = document.querySelector("#wordCount");
textarea.addEventListener("input", () => {
const text = textarea.value;
charCountDisplay.textContent = text.length;
const words = text.trim() ? text.trim().split(/\s+/).length : 0;
wordCountDisplay.textContent = words;
});
Project 4: Filterable Product Catalog via data-* attributes
function filterProducts(category) {
const allProducts = document.querySelectorAll(".product-card");
allProducts.forEach(card => {
const itemCategory = card.dataset.category;
if (category === "all" || itemCategory === category) {
card.style.display = "block";
} else {
card.style.display = "none";
}
});
}
Test dynamic element selection and event handling in our online HTML/JS Editor:
<h1 id="title">Old Title</h1>
<button id="changeButton">Change Title</button>
<script>
const title = document.querySelector("#title");
const button = document.querySelector("#changeButton");
button.addEventListener("click", () => {
title.textContent = "New Title";
});
</script>