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
textContentvsinnerHTMLis also a security decision when data is untrusted.
Navigation: ← 1.14.d — Tree Traversal · 1.14.f — Create & Remove →
1. textContent vs innerHTML
| API | Parses HTML? | Typical use |
|---|---|---|
textContent | No — treats string as plain text | Labels, messages, user nicknames |
innerHTML | Yes — browser parses tags | Rich 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 useclassListinstead (below).- Boolean attributes (
disabled,checked) — setting to any value often enables them; remove withremoveAttributefor 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 fromtextContent(CSS display affects it). Avoid for security boundary; prefertextContentfor pure text assignment.insertAdjacentHTML— parse HTML at a position; same XSS cautions asinnerHTML.
6. Key takeaways
textContentfor untrusted plain text;innerHTMLonly when markup is trusted or sanitized.getAttribute/setAttributemanipulate HTML attributes as strings.classListfor toggling design states;stylefor specific inline overrides.
Explain-It Challenge
Explain without notes:
- Why is assigning user profile text to
innerHTMLdangerous? - When is
setAttributepreferable to a property likeinput.value? - What does
classList.toggle("open", false)do?
Navigation: ← 1.14.d — Tree Traversal · 1.14.f — Create & Remove →