Episode 1 — Fundamentals / 1.14 — DOM Manipulation

1.14.e — Manipulating DOM Elements in JavaScript

In one sentence: You change what users see by updating text, HTML, attributes, inline styles, and classes — choosing textContent vs innerHTML is also a security decision when data is untrusted.

Navigation: ← 1.14.d — Tree Traversal · 1.14.f — Create & Remove →


1. textContent vs innerHTML

APIParses HTML?Typical use
textContentNo — treats string as plain textLabels, messages, user nicknames
innerHTMLYes — browser parses tagsRich markup from trusted sources only
el.textContent = "<b>Hi</b>";   // user sees literal <b>Hi</b>
el.innerHTML = "<b>Hi</b>";     // user sees bold Hi

XSS warning: If innerHTML is fed untrusted data (URLs, names, server JSON), an attacker can inject <script> or event attributes in older patterns. Prefer textContent or safe APIs (createElement, textContent) for user data.


2. getAttribute / setAttribute

HTML attributes map to DOM properties, but not always 1:1. Attribute APIs work on string names:

link.getAttribute("href");
input.setAttribute("aria-expanded", "true");
  • setAttribute("class", "a b") works; usually you use classList instead (below).
  • Boolean attributes (disabled, checked) — setting to any value often enables them; remove with removeAttribute for clarity.

3. The style property

element.style is a CSSStyleDeclaration — set camelCase CSS properties:

box.style.backgroundColor = "navy";
box.style.display = "none";

Inline styles override author stylesheets unless !important wins — good for JS-driven state (e.g. drag position), heavy-handed for design systems (prefer classes).

Reading el.style.width only shows inline values, not values from stylesheets — use getComputedStyle(el) when you need resolved CSS (advanced).


4. classList

element.classList — convenient token list:

el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("selected", isSelected); // force on/off with boolean
el.classList.contains("card");

Prefer classes over many inline style tweaks for maintainability.


5. Other common text APIs (awareness)

  • innerText — layout-aware text extraction; differs from textContent (CSS display affects it). Avoid for security boundary; prefer textContent for pure text assignment.
  • insertAdjacentHTML — parse HTML at a position; same XSS cautions as innerHTML.

6. Key takeaways

  1. textContent for untrusted plain text; innerHTML only when markup is trusted or sanitized.
  2. getAttribute / setAttribute manipulate HTML attributes as strings.
  3. classList for toggling design states; style for specific inline overrides.

Explain-It Challenge

Explain without notes:

  1. Why is assigning user profile text to innerHTML dangerous?
  2. When is setAttribute preferable to a property like input.value?
  3. What does classList.toggle("open", false) do?

Navigation: ← 1.14.d — Tree Traversal · 1.14.f — Create & Remove →