Episode 1 — Fundamentals / 1.14 — DOM Manipulation
1.14.f — Creating & Removing DOM Elements
In one sentence: You build new nodes with
document.createElement, attach them withappendChildorinsertBefore, and detach them withremoveChild— the same patterns power menus, lists, and modals.
Navigation: ← 1.14.e — Manipulating Elements · 1.14 Overview
1. document.createElement(tagName)
Creates an element node in memory — not on screen until inserted.
const li = document.createElement("li");
li.textContent = "New item";
Use createTextNode rarely; textContent on elements is simpler.
2. parent.appendChild(child)
Appends child as the last child of parent. If child was already in the tree, it is moved (not copied).
const ul = document.querySelector("#todo-list");
ul.appendChild(li);
3. parent.insertBefore(newNode, referenceNode)
Inserts newNode immediately before referenceNode under parent.
parent.insertBefore(newNode, parent.firstChild); // prepend pattern
If referenceNode is null, browsers historically treated it like appendChild — but rely on appendChild / modern APIs for append to avoid confusion.
4. parent.removeChild(child)
Removes child from parent and returns the removed node.
const form = document.querySelector("#signup");
const oldBanner = document.querySelector("#banner");
form.removeChild(oldBanner);
Requirement: child must be a direct child of parent — otherwise NotFoundError.
5. Modern shortcuts (know they exist)
| Modern API | Role |
|---|---|
child.remove() | Remove node from its parent (no parent reference needed) |
parent.append(a, b) | Append nodes or strings (variadic) |
insertAdjacentElement / insertAdjacentText | Insert relative to element with position constant |
Interviews and legacy code still use removeChild; new code often uses remove().
6. Document fragments (preview)
document.createDocumentFragment() lets you attach many nodes off-screen, then append the fragment once — fewer reflows for bulk inserts (optimization topic).
7. Key takeaways
createElement→ configure properties →appendChild/insertBeforeto show.appendChildmoves existing nodes — duplicate insertion is impossible withoutcloneNode.removeChildneeds the correct parent reference;element.remove()is simpler today.
Explain-It Challenge
Explain without notes:
- What happens if you call
appendChildon a node that is already somewhere else in the document? - Why does
parent.removeChild(child)throw ifchildis nested insideparent’s descendant but not a direct child? - Write the modern one-liner equivalent of
parent.removeChild(el)whenelis any element.
Navigation: ← 1.14.e — Manipulating Elements · 1.14 Overview