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 with appendChild or insertBefore, and detach them with removeChild — 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 APIRole
child.remove()Remove node from its parent (no parent reference needed)
parent.append(a, b)Append nodes or strings (variadic)
insertAdjacentElement / insertAdjacentTextInsert 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

  1. createElement → configure properties → appendChild / insertBefore to show.
  2. appendChild moves existing nodes — duplicate insertion is impossible without cloneNode.
  3. removeChild needs the correct parent reference; element.remove() is simpler today.

Explain-It Challenge

Explain without notes:

  1. What happens if you call appendChild on a node that is already somewhere else in the document?
  2. Why does parent.removeChild(child) throw if child is nested inside parent’s descendant but not a direct child?
  3. Write the modern one-liner equivalent of parent.removeChild(el) when el is any element.

Navigation: ← 1.14.e — Manipulating Elements · 1.14 Overview