Unit 3: Objects, DOM & Browser Web APIsLesson #8 / 10

Lesson 8: DOM Manipulation, createElement & innerHTML

Er. Manoj Kumar — AuthorEr. Manoj KumarLast Updated: 26 Aug, 2026

1. Mutating the DOM Dynamically

JavaScript enables live element creation, insertion, removal, and style mutations:

  • document.createElement('div'): Creates a new detached DOM node.
  • parent.appendChild(node): Appends node as the last child.
  • element.classList.add / remove / toggle: Manipulates CSS classes cleanly.
  • element.setAttribute('key', 'value'): Sets HTML attribute properties.
  • HTML5 Web Code (index.html)
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>DOM Mutation Studio</title>
    </head>
    <body style="background:#17181c; color:#fff; font-family:Arial; padding:30px;">
    <h2>Dynamic Card Builder</h2>
    <button id="add-card-btn" style="padding:10px 18px; background:#04AA6D; color:#fff; border:none; border-radius:6px; font-weight:bold; cursor:pointer;">
    + Add New Project Card
    </button>
    <div id="cards-container" style="margin-top:20px; display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:12px;"></div>
    <script>
    let cardCount = 0;
    const btn = document.getElementById("add-card-btn");
    const container = document.getElementById("cards-container");
    btn.addEventListener("click", () => {
    cardCount++;
    const card = document.createElement("div");
    card.style.background = "#1f2029";
    card.style.padding = "16px";
    card.style.borderRadius = "8px";
    card.style.border = "1px solid #333";
    card.innerHTML = `<h4 style="color:#04AA6D; margin:0 0 8px 0;">Project #${cardCount}</h4><p style="margin:0; font-size:12px; color:#aaa;">Created via DOM createElement</p>`;
    container.appendChild(card);
    });
    </script>
    </body>
    </html>

    Interactive Knowledge Check

    Test your understanding of Lesson #8 concepts

    Which method safely sets text content inside an HTML element without creating XSS vulnerability risks?