Topic 02 / 10

DOM Manipulation: Create, Append & ClassList

1. Simple Definition

DOM Manipulation ka matlab hai live webpage ke andar naye HTML elements create karna (createElement), unhe page par jodna (append), purane elements ko delete karna (remove), aur CSS classes ko dynamically add/remove/toggle karna (classList).

2. Real-Life Analogy

🎭 Live Theater Stage Decorator

Live natak chal raha hai. Stage decorator piche se ek naya artificial tree lekar aata hai aur stage par fix kar deta hai (createElement + append). Fir light inspector aakar button dabata hai aur deewar par Blue lights on ho jaati hain (classList.toggle('active')). Aur scene khatam hone par purane props utha kar bahar phenk deta hai (remove())!

3. Why Do We Need It?

To-Do List app me "Add Task" dabane par naya task judna, Chat app me naya message box aana, aur Dark Mode toggle karne par body par class lagna DOM Manipulation se hi hota hai.

4. Syntax

// 1. Creating a New Element
const newCard = document.createElement("div");

// 2. Adding Classes & Attributes
newCard.classList.add("card", "shadow-md");
newCard.setAttribute("data-status", "active");
newCard.textContent = "Naya Dynamic Item!";

// 3. Appending to Page Container
const container = document.querySelector("#cards-container");
container.append(newCard); // Modern append (accepts text & elements)

// 4. ClassList Mastery
element.classList.add("active");
element.classList.remove("hidden");
element.classList.toggle("dark-mode"); // Agar hai toh hatao, nahi hai toh lagao
const hasClass = element.classList.contains("active"); // true/false

// 5. Deleting an Element
newCard.remove(); // Instantly removes from DOM

5. Basic Example (Dynamic Task Adder)

<div style="max-width: 400px;">
  <div style="display:flex; gap:8px; margin-bottom:1rem;">
    <input type="text" id="task-input" placeholder="Naya task likhein..." class="search-input" style="border:1px solid #ccc; padding:6px;">
    <button id="add-btn" class="btn btn-primary">Add</button>
  </div>
  <ul id="tasks-list" style="list-style:none; padding:0;"></ul>
</div>

<script>
  const input = document.getElementById("task-input");
  const addBtn = document.getElementById("add-btn");
  const list = document.getElementById("tasks-list");

  addBtn.addEventListener("click", () => {
    const text = input.value.trim();
    if (!text) return;

    // 1. Create LI
    const li = document.createElement("li");
    li.style = "display:flex; justify-content:space-between; padding:8px; background:#f1f5f9; margin-bottom:4px; border-radius:4px;";
    li.textContent = text;

    // 2. Create Delete Button
    const delBtn = document.createElement("button");
    delBtn.textContent = "❌";
    delBtn.style = "background:transparent; border:none; cursor:pointer;";
    delBtn.onclick = () => li.remove(); // Self delete!

    li.append(delBtn);
    list.append(li);
    input.value = ""; // Reset input
  });
</script>

6. Output / Expected Result

    7. Code Explanation

    • document.createElement("tag"): Memory me naya element banata hai (ye tab tak screen par nahi dikhta jab tak aap append() na karein).
    • append() vs appendChild(): Modern append() ek sath multiple elements aur direct text strings dono ko jod sakta hai.
    • classList.toggle("name"): Agar class pehle se hai toh hata deta hai, agar nahi hai toh add kar deta hai (Dark theme switchers ke liye best).
    • element.remove(): Modern baseline method jo element ko direct DOM se delete karta hai bina parent dhoondhe!

    8. Real-World Example

    Twitter/X par jab aap "Post" button dabate hain, toh bina page refresh hue aapka naya tweet feed ke sabhi puraane tweets ke upar prepend() ho jata hai.

    9. Common Mistakes: Loop me innerHTML use karna

    ⚠️ Loop me list.innerHTML += '...' ka Performance Catastrophe

    Agar aap 100 items loop karte waqt har bar list.innerHTML += '<li>...</li>' likhte hain, toh browser har ek item par poore 100 elements ko delete karke dobara shuru se parse karta hai!
    Solution: DocumentFragment use karein ya createElement se memory me banakar ek hi bar append karein.

    10. Best Practices

    • Styling ke liye element.style.color = "red" ke bajaye hamesha element.classList.add("text-error") use karein (Separation of concerns!).
    • Bulk items insert karne ke liye const fragment = document.createDocumentFragment(); use karein.

    11. Try It Yourself

    Playground me ek button click par page ke background par document.body.classList.toggle("custom-bg") chala kar dekhein.

    12. Challenge

    Ek dynamic Notification Toast container banayein jo button click par green banner banaye aur 3 second baad setTimeout() se automatically toast.remove() ho jaye!

    13. Interview Questions

    💼 Q: DocumentFragment kya hota hai aur ye rendering speed kaise badhata hai?

    Answer: DocumentFragment ek lightweight virtual container hota hai jo memory me rehta hai aur main DOM tree ka part nahi hota. Isme hazaron elements add karne par koi Reflow/Repaint nahi hota. Jab fragment ko main DOM me ek bar parent.appendChild(fragment) karte hain, toh single reflow me saare elements inject ho jaate hain!

    14. Quick Revision

    • document.createElement("tag") creates in memory.
    • parent.append(child) connects to screen.
    • element.remove() cleanly deletes.
    • classList.toggle() simplifies UI states.

    15. FAQ

    Q1. prepend() aur append() me kya fark hai?

    append() container ke aakhri me jodta hai (bottom). prepend() container ke bilkul shuru me jodta hai (top).

    Q2. replaceWith() method kya karta hai?

    Kisi existing DOM element ko direct naye element se replace kar deta hai.

    Q3. cloneNode(true) kya karta hai?

    Element aur uske sabhi child elements ki exact duplicate copy banata hai.

    Q4. dataset property se attribute kaise set karein?

    element.dataset.userId = "123"; HTML me automatically data-user-id="123" create kar deta hai.

    Q5. closest() selector kya karta hai?

    Current element se upar ki taraf chalte hue matching parent element dhoondhta hai (e.g. btn.closest('.card')).

    Topic 02 / 10

    DOM Manipulation: Create, Append & ClassList

    1. Simple Definition

    DOM Manipulation is the active process of creating, inserting, styling, modifying, and removing HTML elements dynamically using JavaScript. Core methods include document.createElement(), append(), remove(), and class management via classList.

    2. Real-Life Analogy

    📋 Whiteboard Task List

    Writing a new sticky task note on paper (createElement), sticking it on the conference room board (append), changing its color badge from "Pending" to "Done" (classList.toggle), and crumpling it up to throw into the trash (remove)!

    3. Creating and Inserting Elements Safely

    // 1. Create a new element
    const newCard = document.createElement("div");
    
    // 2. Add class and safe text content
    newCard.classList.add("notification-card", "active");
    newCard.textContent = "New update available!";
    
    // 3. Append to parent container
    const container = document.querySelector("#alert-container");
    container.append(newCard); // Modern multi-node insertion

    4. The Power of classList

    Method Action
    classList.add("dark") Adds class if not already present
    classList.remove("hidden") Removes class if present
    classList.toggle("active") Adds class if absent; removes if already present
    classList.contains("selected") Returns boolean check (true/false)

    5. innerHTML vs textContent (Security Non-Negotiable)

    ⚠️ Security Warning: Never use innerHTML for user inputs!

    Inserting untrusted user text with innerHTML creates devastating Cross-Site Scripting (XSS) vulnerabilities! Always use textContent or create nodes safely with document.createElement()!

    6. Best Practices

    • Use element.classList instead of mutating element.className directly.
    • Use DocumentFragment when appending multiple items to minimize browser reflows.
    • Use element.remove() for clean self-deletion.

    7. Practice Exercise

    🎯 Exercise: Dynamic To-Do Creator

    Create an input and a button. When clicked, create a new <li> item containing the input's text, append it to an existing <ul>, and clear the input field.

    8. Interview Questions

    💼 Q: Why is DocumentFragment useful during bulk DOM insertions?

    Answer: Appending 1,000 individual elements directly to the DOM triggers 1,000 separate browser reflows. Appending them all to an in-memory DocumentFragment first and appending the fragment once triggers only a single reflow.

    9. Summary / Cheat Card

    • createElement() instantiates new DOM nodes.
    • append() inserts nodes into parent containers.
    • classList.toggle() simplifies UI state switching.
    • Always prefer textContent over innerHTML.

    10. FAQ

    Q1. What is the difference between appendChild() and append()?

    append() is modern: it accepts multiple nodes and strings directly, whereas appendChild() accepts only a single Node and returns it.