TutorialsJavaScriptDOM Manipulation
JavaScript

DOM Manipulation

The DOM (Document Object Model) is a tree representation of your HTML page. JavaScript can read, modify, add, or remove any element in real time — this is what makes web pages interactive.

// ── Selecting Elements ──────────────────────────────────────────────
const title  = document.getElementById("main-title");      // single, by id
const btn    = document.querySelector(".submit-btn");       // first match (CSS selector)
const allCards = document.querySelectorAll(".card");        // NodeList of ALL matches
allCards.forEach(card => console.log(card.textContent));

// ── Reading & Changing Content ──────────────────────────────────────
title.textContent = "New Title";               // safe — no HTML parsing
title.innerHTML   = "<em>Italic</em>";         // renders HTML (XSS risk with user input!)

// ── Changing Styles ─────────────────────────────────────────────────
title.style.color    = "navy";
title.style.fontSize = "2rem";

// ── CSS Classes (preferred over inline styles) ──────────────────────
btn.classList.add("active");
btn.classList.remove("disabled");
btn.classList.toggle("hidden");           // add if absent, remove if present
btn.classList.contains("active");         // true or false

// ── Attributes ─────────────────────────────────────────────────────
const link = document.querySelector("a");
console.log(link.getAttribute("href"));
link.setAttribute("target", "_blank");
link.removeAttribute("disabled");

// ── Creating & Adding Elements ──────────────────────────────────────
const li = document.createElement("li");
li.textContent = "New item";
li.classList.add("task-item");

const ul = document.querySelector("ul");
ul.appendChild(li);         // add at end
ul.prepend(li);             // add at beginning
ul.insertBefore(li, ul.firstChild); // insert before specific child

// ── Removing Elements ───────────────────────────────────────────────
document.querySelector(".outdated").remove();

// ── Traversal ───────────────────────────────────────────────────────
const item = document.querySelector(".item");
console.log(item.parentElement);          // parent node
console.log(item.children);              // child elements
console.log(item.nextElementSibling);    // next sibling element
console.log(item.previousElementSibling);// previous sibling
💡

textContent vs innerHTML: Use textContent when setting plain text — it escapes HTML characters and is safe against XSS attacks. Only use innerHTML when you intentionally need to inject HTML markup, and never with untrusted user input.

Watch & Learn

A recommended video to watch alongside this chapter.

More “DOM Manipulation” videos on YouTube