Episode 1 — Fundamentals / 1.14 — DOM Manipulation
1.14 — DOM Manipulation: Quick Revision
Compact cheat sheet. Print-friendly.
How to use this material (instructions)
- Skim before labs or interviews.
- Drill gaps — reopen
README.md→1.14.a…1.14.f. - Practice —
1.14-Exercise-Questions.md. - Polish answers —
1.14-Interview-Questions.md.
Core vocabulary
| Term | One-liner |
|---|---|
| DOM | Live object tree of the document |
| Node | Any tree item (element, text, comment, …) |
| Element | Node that is an HTML element |
document | Root Document object; global entry point |
Selecting elements
| API | Returns | Live? |
|---|---|---|
getElementById(id) | Element | null | — |
getElementsByTagName(tag) | HTMLCollection | Yes |
getElementsByClassName(classes) | HTMLCollection | Yes |
querySelector(sel) | Element | null | — |
querySelectorAll(sel) | NodeList | No (snapshot) |
Scope: element.querySelector(...) limits search subtree.
Traversal cheat sheet
| All node types | Elements only |
|---|---|
parentNode | parentElement |
childNodes | children |
firstChild / lastChild | firstElementChild / lastElementChild |
previousSibling / nextSibling | previousElementSibling / nextElementSibling |
Whitespace in HTML → text nodes → firstChild surprises.
Changing content & attributes
| API | Use |
|---|---|
textContent | Plain text (no HTML parse) — safe for untrusted text |
innerHTML | Parses HTML — XSS risk if untrusted |
getAttribute / setAttribute / removeAttribute | HTML attributes as strings |
element.style.prop | Inline CSS (camelCase) |
element.classList | add / remove / toggle / contains |
Create / insert / remove
const el = document.createElement("div");
parent.appendChild(el); // append last child
parent.insertBefore(el, parent.firstChild); // prepend pattern
parent.removeChild(child); // legacy; needs direct parent
child.remove(); // modern
appendChild on existing node → moves it (no duplicate).
Security (remember)
Untrusted data → never innerHTML
→ textContent or createElement + append
Master workflow
- Select —
getElementById/ scopedquerySelector(All). - Traverse — prefer
*Element*properties for UI. - Mutate —
textContent/ attributes /classList/style. - Create —
createElement→ configure →appendChild/insertBefore. - Remove —
remove()orremoveChild(legacy).
End of 1.14 quick revision.