Topic 07 / 15

The DOM — Selecting & Manipulating Elements

~11 min read  //  JavaScript Series  //  Coding India

What the DOM Is

The browser parses your HTML into a live tree of objects — the Document Object Model. JavaScript reads and rewrites that tree, and the page updates instantly. Every framework (React, Vue) is ultimately doing this under the hood.

Selecting Elements

// CSS selectors — the modern way
const title = document.querySelector("#title");        // first match
const cards = document.querySelectorAll(".card");      // all matches (NodeList)
const firstLink = document.querySelector("nav a");

cards.forEach(card => console.log(card));

Changing Content

title.textContent = "Hello Coding India";   // text only — safe
title.innerHTML = "<em>Hello</em>";          // parses HTML — XSS risk with user data!

Rule: use textContent for anything user-supplied. innerHTML with untrusted input is how sites get hacked.

Attributes, Styles & Classes

const img = document.querySelector("img");
img.src = "logo.png";
img.setAttribute("alt", "Coding India");
img.dataset.userId = "42";                 // data-user-id="42"

title.style.color = "#6366F1";             // inline style (one-offs only)

// classes — the right way to change appearance
title.classList.add("active");
title.classList.remove("hidden");
title.classList.toggle("dark");
title.classList.contains("active")         // true

Prefer toggling classes (with the styles in CSS) over setting inline styles — it keeps design in stylesheets where it belongs.

Creating & Removing Elements

const li = document.createElement("li");
li.textContent = "New item";
li.classList.add("item");

const list = document.querySelector("#list");
list.append(li);            // add at the end
list.prepend(li);           // or the start
li.remove();                // delete it

Rendering a List From Data

The pattern behind every dynamic UI — data in, DOM out:

const courses = [
  { title: "Django", price: 199 },
  { title: "React", price: 149 },
];

const list = document.querySelector("#courses");
list.innerHTML = "";                       // clear

for (const course of courses) {
  const li = document.createElement("li");
  li.textContent = `${course.title} — ₹${course.price}`;
  list.append(li);
}

Traversal

el.parentElement
el.children
el.closest(".card")        // nearest ancestor matching a selector
el.nextElementSibling

closest() becomes essential for event delegation — next topic.