DOM Manipulation

📖 Concept

The DOM (Document Object Model) is a tree representation of your HTML that JavaScript can interact with. Every HTML element becomes a node that you can select, create, modify, or remove.

Selecting: querySelector, querySelectorAll, getElementById, getElementsByClassName Creating: createElement, createTextNode, cloneNode Modifying: textContent, innerHTML, classList, setAttribute, style Inserting: appendChild, prepend, append, insertBefore, insertAdjacentHTML Removing: remove, removeChild

🏠 Real-world analogy: The DOM is like a family tree. querySelector is like searching for a specific family member. appendChild is like adding a newborn to the family.

💻 Code Example

codeTap to expand ⛶
1// Selecting elements
2const heading = document.querySelector("h1"); // First match
3const allCards = document.querySelectorAll(".card"); // All matches (NodeList)
4const byId = document.getElementById("main"); // By ID
5
6// Creating elements
7const div = document.createElement("div");
8div.textContent = "Hello, World!";
9div.classList.add("card", "active");
10div.setAttribute("data-id", "42");
11div.style.backgroundColor = "#1a1a2e";
12
13// Inserting into the DOM
14document.body.appendChild(div);
15heading.insertAdjacentHTML("afterend", "<p>Subtitle here</p>");
16
17// Modifying existing elements
18heading.textContent = "New Title"; // Safe (no HTML parsing)
19heading.innerHTML = "<em>Styled</em> Title"; // Parses HTML (XSS risk!)
20heading.classList.toggle("active");
21heading.classList.replace("old-class", "new-class");
22
23// Traversing the DOM
24const parent = div.parentElement;
25const children = parent.children; // HTMLCollection (live)
26const next = div.nextElementSibling;
27const prev = div.previousElementSibling;
28
29// Removing elements
30div.remove(); // Modern
31// parent.removeChild(div); // Legacy
32
33// Batch DOM updates with DocumentFragment (performance)
34const fragment = document.createDocumentFragment();
35for (let i = 0; i < 100; i++) {
36 const li = document.createElement("li");
37 li.textContent = `Item ${i + 1}`;
38 fragment.appendChild(li);
39}
40document.querySelector("ul").appendChild(fragment); // Single reflow!

🏋️ Practice Exercise

Mini Exercise:

  1. Create a function that builds a card component from data (title, description, image URL)
  2. Write a function to dynamically create a table from a 2D array
  3. Implement a toggle dark/light mode button that switches CSS classes
  4. Build a simple todo list with add and delete functionality using DOM manipulation

⚠️ Common Mistakes

  • Using innerHTML for user-generated content — XSS vulnerability! Use textContent instead

  • Querying the DOM inside a loop — cache the element reference outside the loop for performance

  • querySelectorAll returns a NodeList, not an Array — use Array.from() or spread [...] to use array methods

  • Modifying DOM in a loop causes reflow for each operation — use DocumentFragment for batch inserts

  • getElementsByClassName returns a live HTMLCollection that updates automatically — this can cause unexpected behavior in loops

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for DOM Manipulation. Login to unlock this feature.