Episode 1 — Fundamentals / 1.14 — DOM Manipulation
Interview Questions: DOM Manipulation
Model answers for DOM vs HTML, nodes vs elements, query APIs, live collections, traversal, XSS / innerHTML, and insert/remove patterns.
How to use this material (instructions)
- Read lessons in order —
README.md, then1.14.a→1.14.f. - Practice out loud — definition → example → pitfall.
- Pair with exercises —
1.14-Exercise-Questions.md. - Quick review —
1.14-Quick-Revision.md.
Beginner (Q1–Q4)
Q1. What is the DOM?
Why interviewers ask: Confirms you connect HTML to the in-memory tree browsers use.
Model answer:
The Document Object Model (DOM) is a tree of objects the browser creates when it parses HTML. Each node represents part of the document (elements, text, comments). JavaScript uses the DOM API (document, querySelector, etc.) to read and mutate the tree, which updates what the user sees without editing the source file on disk.
Q2. Explain getElementById vs querySelector.
Why interviewers ask: Everyday selection + performance intuition.
Model answer:
getElementById("x") looks up a single element by id string (no #) and returns Element or null. It is highly optimized in browsers. querySelector("#x") uses the CSS selector engine — more flexible (complex selectors) but slightly more overhead for simple ID lookups. For IDs, getElementById is idiomatic; for patterns, querySelector / querySelectorAll.
Q3. What is the difference between childNodes and children?
Why interviewers ask: Classic “why is my script broken?” question (whitespace text nodes).
Model answer:
childNodes is a NodeList of all child nodes — including text nodes (often whitespace between tags) and comments. children is an HTMLCollection of only element children. For UI traversal, children / firstElementChild / nextElementSibling are usually safer. childNodes matters when you intentionally process text or legacy code relies on it.
Q4. Why is innerHTML with user input dangerous?
Why interviewers ask: XSS is a core web security topic.
Model answer:
innerHTML parses a string as HTML. If that string contains untrusted user data, an attacker can inject scripts or event handlers (depending on context and sanitization), leading to cross-site scripting (XSS) — stealing cookies, session tokens, or performing actions as the user. Prefer textContent, createElement + appendChild, or a trusted sanitizer / framework escaping strategy for untrusted content.
Intermediate (Q5–Q8)
Q5. What does it mean that getElementsByTagName returns a “live” collection?
Why interviewers ask: Bugs from mutating DOM while iterating a live list.
Model answer:
A live HTMLCollection reflects the DOM as it changes. If you add or remove matching elements, indices and length update automatically. querySelectorAll returns a static NodeList — a snapshot at query time; later DOM changes do not update the list. Loops that modify the DOM must account for live collections re-indexing or copy to an array first.
Q6. What happens when you appendChild a node that is already in the document?
Why interviewers ask: Tests understanding of single ownership in the tree.
Model answer:
A node can have only one parent. appendChild on an already attached node moves it from its old parent to the new parent — it does not duplicate. To duplicate, use cloneNode(true) (deep clone) then append the clone.
Q7. Compare textContent, innerText, and innerHTML.
Why interviewers ask: Correct tool choice + security + layout.
Model answer:
textContent— reads/writes raw text; does not parse HTML when setting — safest default for injecting user-visible strings.innerHTML— parses HTML; powerful but XSS risk with untrusted data.innerText— reflects rendered text as a user would see; affected by CSS likedisplay:none; slower and less predictable for assignment thantextContentfor simple cases.
Q8. How does classList compare to element.className?
Why interviewers ask: Maintainable class toggling in components.
Model answer:
className is a single string of all classes — easy to overwrite accidentally. classList is a DOMTokenList with add, remove, toggle, and contains — avoids string parsing bugs and race conditions when multiple scripts update classes. Prefer classList for incremental updates.
Advanced (Q9–Q11)
Q9. When might removeChild still be preferred over element.remove()?
Why interviewers ask: Legacy maintenance + explicit parent/child invariants.
Model answer:
element.remove() (modern) removes the node from its parent without fetching the parent reference. parent.removeChild(child) is the older pattern and throws if child is not a direct child — that can enforce explicit invariants in legacy code. New code typically uses remove() or replaceWith() for clarity. Interviews may ask you to recognize removeChild in older libraries.
Q10. What is the difference between attributes and properties on DOM elements?
Why interviewers ask: Confusion around value, checked, href.
Model answer:
Attributes are in the HTML serialization (<input value="x">). Properties are JavaScript object fields on the DOM object (input.value). They are mirrored for many cases but can diverge (e.g. defaultValue vs value, getAttribute("value") vs current value). Use getAttribute / setAttribute when you need the HTML attribute string (e.g. initial config, data-*), and properties for current UI state (checked, live value).
Q11. How does insertBefore(newNode, referenceNode) behave if referenceNode is null?
Why interviewers ask: Edge-case knowledge (browser compatibility historically varied).
Model answer:
Historically some browsers treated insertBefore(node, null) like appendChild. The spec behavior should be relied on carefully — prefer appendChild for appending or use insertBefore with a known reference (e.g. firstChild) or modern append / prepend for clarity. In interviews, stating “avoid null reference; use explicit APIs” shows good judgment.
Quick-fire
| # | Question | One-line answer |
|---|---|---|
| 1 | querySelectorAll live? | No — static NodeList |
| 2 | firstChild vs firstElementChild | First any node vs first element |
| 3 | Move node to new parent | appendChild same node |
| 4 | Safe user string into DOM | textContent or createTextNode |
| 5 | Toggle class if present | classList.toggle("x") |
← Back to 1.14 — DOM Manipulation (README)