DOM Manipulation & Web Interactivity (Selecting, Modifying, Events & Dynamic Lists)

๐ŸŸจ JavaScript (ES2026+) ๐ŸŸข Lesson 14 ๐Ÿ“‚ Phase 11: DOM Manipulation ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this lesson: DOM Architecture ยท Selecting Elements ยท textContent vs innerHTML ยท Styles & classList ยท Reading Inputs ยท createElement & append ยท dataset Attributes ยท Traversal & closest() ยท Dynamic Lists ยท 4 Interactive Projects

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.

1DOM Ante Enti? (Tree Architecture & In-Memory Representation)

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:

window
โ””โ”€โ”€ document (Document Object)
    โ””โ”€โ”€ <html>
        โ”œโ”€โ”€ <head> (title, meta, links)
        โ””โ”€โ”€ <body>
            โ”œโ”€โ”€ <h1 id="title">Old Title</h1>
            โ””โ”€โ”€ <button id="changeButton">Change Title</button>
2Selecting Elements (getElementById vs querySelector vs querySelectorAll)
MethodSelector SyntaxReturn TypeDescription
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 & JavaScript โ€” Title Changer Example โ–ถ Try in HTML/JS Editor
<!-- 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>
3Changing Text & HTML: textContent vs innerHTML
1. textContent (โญ Safe & Fast)

Element lopali raw plain text ni update chesthundi. HTML tags ni text gane treat chesthundi, preventing XSS (Cross-Site Scripting) attacks!

2. innerHTML (โš ๏ธ Use with Caution)

HTML tags ni parse chesi render chesthundi (e.g. <strong>Bold</strong>). User input ni direct ga innerHTML lo inject cheyyakudadhu!

JavaScript โ€” textContent vs innerHTML
"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>!";
4Changing Styles & classList (add, remove, toggle, contains)

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 boolean true/false.
JavaScript โ€” classList in Action
"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!");
}
5Creating, Appending & Removing Elements (DOM Tree Mutations)
MethodDescriptionExample
document.createElement(tag)Creates new unattached DOM element nodeconst 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 parentlist.prepend(newLi);
element.remove()Removes the element directly from DOM treeitem.remove();
JavaScript โ€” Dynamic Element Creation
"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();
6Data Attributes (dataset) & DOM Traversal (closest)
  • Data Attributes (data-*): Custom metadata stored on HTML tags: <button data-user-id="101" data-action="delete"> $ ightarrow$ read with button.dataset.userId and button.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!).
74 Interactive Real-World Browser Projects

Mastering DOM manipulation through 4 complete production components:

Project 1: Dynamic Task Manager (Create, Toggle, Delete)

HTML + JavaScript โ€” Interactive Todo List โ–ถ Try in Editor
<!-- 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

JavaScript โ€” Theme 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

JavaScript โ€” Live Input Analytics
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

JavaScript โ€” Catalog Filter
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";
        }
    });
}
๐Ÿ’ป Try It Yourself โ€” User Curriculum Code Example

Test dynamic element selection and event handling in our online HTML/JS Editor:

HTML + JavaScript โ–ถ Open 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>
Open in HTML/CSS/JS Editor โ†’
OC
Written and reviewed by Our Compiler Technical Team ยท Updated for JavaScript ES2026+