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
1// Selecting elements2const heading = document.querySelector("h1"); // First match3const allCards = document.querySelectorAll(".card"); // All matches (NodeList)4const byId = document.getElementById("main"); // By ID56// Creating elements7const div = document.createElement("div");8div.textContent = "Hello, World!";9div.classList.add("card", "active");10div.setAttribute("data-id", "42");11div.style.backgroundColor = "#1a1a2e";1213// Inserting into the DOM14document.body.appendChild(div);15heading.insertAdjacentHTML("afterend", "<p>Subtitle here</p>");1617// Modifying existing elements18heading.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");2223// Traversing the DOM24const parent = div.parentElement;25const children = parent.children; // HTMLCollection (live)26const next = div.nextElementSibling;27const prev = div.previousElementSibling;2829// Removing elements30div.remove(); // Modern31// parent.removeChild(div); // Legacy3233// 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:
- Create a function that builds a card component from data (title, description, image URL)
- Write a function to dynamically create a table from a 2D array
- Implement a toggle dark/light mode button that switches CSS classes
- Build a simple todo list with add and delete functionality using DOM manipulation
⚠️ Common Mistakes
Using
innerHTMLfor user-generated content — XSS vulnerability! UsetextContentinsteadQuerying the DOM inside a loop — cache the element reference outside the loop for performance
querySelectorAllreturns a NodeList, not an Array — useArray.from()or spread[...]to use array methodsModifying DOM in a loop causes reflow for each operation — use
DocumentFragmentfor batch insertsgetElementsByClassNamereturns 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.