Episode 1 — Fundamentals / 1.14 — DOM Manipulation

1.14 — DOM Manipulation: Quick Revision

Compact cheat sheet. Print-friendly.

How to use this material (instructions)

  1. Skim before labs or interviews.
  2. Drill gaps — reopen README.md1.14.a1.14.f.
  3. Practice1.14-Exercise-Questions.md.
  4. Polish answers1.14-Interview-Questions.md.

Core vocabulary

TermOne-liner
DOMLive object tree of the document
NodeAny tree item (element, text, comment, …)
ElementNode that is an HTML element
documentRoot Document object; global entry point

Selecting elements

APIReturnsLive?
getElementById(id)Element | null
getElementsByTagName(tag)HTMLCollectionYes
getElementsByClassName(classes)HTMLCollectionYes
querySelector(sel)Element | null
querySelectorAll(sel)NodeListNo (snapshot)

Scope: element.querySelector(...) limits search subtree.


Traversal cheat sheet

All node typesElements only
parentNodeparentElement
childNodeschildren
firstChild / lastChildfirstElementChild / lastElementChild
previousSibling / nextSiblingpreviousElementSibling / nextElementSibling

Whitespace in HTML → text nodesfirstChild surprises.


Changing content & attributes

APIUse
textContentPlain text (no HTML parse) — safe for untrusted text
innerHTMLParses HTML — XSS risk if untrusted
getAttribute / setAttribute / removeAttributeHTML attributes as strings
element.style.propInline CSS (camelCase)
element.classListadd / 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 nodemoves it (no duplicate).


Security (remember)

Untrusted data  →  never innerHTML
                  →  textContent or createElement + append

Master workflow

  1. SelectgetElementById / scoped querySelector(All).
  2. Traverse — prefer *Element* properties for UI.
  3. MutatetextContent / attributes / classList / style.
  4. CreatecreateElement → configure → appendChild / insertBefore.
  5. Removeremove() or removeChild (legacy).

End of 1.14 quick revision.