Skip to main content

DOM Manipulation


What is the DOM?

The Document Object Model (DOM) is a tree-like representation of an HTML document. JavaScript can access and modify this tree to dynamically change the page.

document
└─ html
├─ head
| └─ title
└─ body
├─ h1
└─ div
└─ p

Selecting Elements

// By ID (returns single element or null)
document.getElementById("myId");

// By class name (returns HTMLCollection, live)
document.getElementsByClassName("myClass");

// By tag name (returns HTMLCollection, live)
document.getElementsByTagName("p");

// CSS Selector (returns FIRST match or null)
document.querySelector(".container h1");
document.querySelector("#main > .item:first-child");

// CSS Selector (returns ALL matches as NodeList)
document.querySelectorAll(".card");
document.querySelectorAll("input[type=text]");

// Convert NodeList to Array
Array.from(document.querySelectorAll(".item"));
[...document.querySelectorAll(".item")];

Traversing the DOM

const el = document.querySelector(".parent");

// Children
el.children; // HTMLCollection of child elements
el.childNodes; // NodeList (includes text/comment nodes)
el.firstElementChild; // first child element
el.lastElementChild; // last child element

// Parent
el.parentElement; // parent element

// Siblings
el.previousElementSibling;
el.nextElementSibling;

// Find closest ancestor matching selector
el.closest(".wrapper");

Reading & Modifying Content

const div = document.querySelector("#app");

// Reading
div.textContent; // plain text (no HTML)
div.innerHTML; // HTML string
div.innerText; // visible text (respects CSS)

// Modifying
div.textContent = "Hello World";
div.innerHTML = "<strong>Bold</strong>"; // ⚠️ XSS risk with user input!

// Attributes
div.getAttribute("class");
div.setAttribute("data-id", "123");
div.removeAttribute("disabled");
div.hasAttribute("hidden");

// Properties
div.id;
div.className; // full class string
div.classList; // DOMTokenList (preferred)

CSS Classes

const el = document.querySelector(".box");

el.classList.add("active"); // add class
el.classList.remove("hidden"); // remove class
el.classList.toggle("dark-mode"); // add if absent, remove if present
el.classList.contains("active"); // true/false
el.classList.replace("old", "new"); // replace class

Styles

const el = document.querySelector(".box");

// Inline styles (camelCase)
el.style.color = "red";
el.style.backgroundColor = "blue";
el.style.fontSize = "18px";

// Read computed styles
getComputedStyle(el).fontSize;

// CSS Custom Properties
el.style.setProperty("--color", "red");
el.style.getPropertyValue("--color");

Creating, Inserting & Removing Elements

// Create element
const newDiv = document.createElement("div");
newDiv.className = "card";
newDiv.textContent = "New Card";
newDiv.setAttribute("data-id", "1");

// Insert into DOM
document.body.appendChild(newDiv); // append to end
document.body.prepend(newDiv); // insert at start

// Modern insertion
parent.append(newDiv, "text"); // multiple nodes
newDiv.before(anotherEl); // insert before element
newDiv.after(anotherEl); // insert after element
newDiv.replaceWith(replacementEl); // replace element

// Remove element
newDiv.remove();
parent.removeChild(newDiv);

// Clone element
const clone = newDiv.cloneNode(true); // deep clone with children

innerHTML vs createElement

// innerHTML — fast but XSS risk with user input!
const userInput = "<img onerror=alert(1) src=x>";
document.body.innerHTML = userInput; // DANGEROUS!

// createElement — safe, always use for user-generated content
const p = document.createElement("p");
p.textContent = userInput; // safely escaped as text

MCQ — DOM Manipulation

Q1: What does querySelector return if no element matches?

A) An empty array B) undefined C) nullD) An empty NodeList

Answer: C

Q2: What is the difference between textContent and innerHTML?

A) No difference B) textContent returns plain text; innerHTML returns HTML markup ✅ C) innerHTML is safer D) textContent parses HTML

Answer: B

Q3: Which method adds a class without removing existing classes?

A) el.className = "newClass" (replaces all!) B) el.classList.add("newClass")C) el.setAttribute("class", "newClass") (replaces all!)

Answer: B

Q4: What does querySelectorAll return?

A) An HTMLCollection B) An Array C) A NodeList ✅ D) A single element

Answer: C

Q5: What is the risk of using innerHTML with user input?

A) Performance issues B) XSS (Cross-Site Scripting) attacks ✅ C) Memory leaks D) Incorrect styling

Answer: B

Q6: What does el.closest(".wrapper") do?

A) Finds the nearest child matching the selector B) Finds the nearest ancestor (including itself) matching the selector ✅ C) Finds the next sibling matching the selector

Answer: B

Q7: How do you remove an element in modern JavaScript?

A) element.delete() B) document.remove(element) C) element.remove()D) element.destroy()

Answer: C