🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

JavaScript and the DOM: Select, Update, and Listen

JavaScriptđŸŸĸ Free Lesson

JavaScript and the DOM

When a browser finishes parsing HTML it builds a live tree of objects called the Document Object Model. Every element becomes a node you can query, modify, and listen on. The DOM is not the HTML you wrote — it is the browser's in-memory representation, and every change you make to it updates what the reader sees, instantly, without a page reload.

This lesson covers the working developer's DOM skill set: selecting elements without ambiguity, reading and writing content safely, wiring events that survive dynamic content, and building a small interactive feature from scratch.

What the DOM Actually Is

The document is a node tree rooted at the document object. Elements, text runs, and comments are nodes; elements can also expose live collections — childNodes, classList, attributes — that reflect later changes automatically. Because the tree is live, grabbing a reference once is safe: the same object keeps pointing at the same element even after its children change.

Two related but different concepts trip people up. The DOM API is the set of methods and properties (querySelector, textContent, addEventListener). The DOM standard also defines the accessibility tree, which assistive technologies consume. Good DOM practice keeps both in sync: semantic elements, correct attributes, and sensible ids.

Querying Elements Precisely

Selection methods differ in return type and capability, and choosing the wrong one is the root of many subtle bugs.

MethodReturnsNotes
getElementByIdSingle element or nullFastest; ids must be unique
querySelectorFirst match or nullAccepts any CSS selector
querySelectorAllStatic NodeListSnapshot — later DOM changes do not appear
getElementsByClassNameLive HTMLCollectionUpdates automatically; class-only
getElementsByTagNameLive HTMLCollectionUpdates automatically; tag-only

Prefer querySelector and querySelectorAll unless you are profiling a hot loop. Their static snapshots make behavior predictable: to see new elements, query again.

javascript
const form = document.querySelector("#signup");
const fields = form.querySelectorAll("input[required]");

console.log("Required fields:", fields.length);

for (const field of fields) {
  field.addEventListener("blur", () => {
    field.classList.toggle("is-invalid", !field.checkValidity());
  });
}

Reading and Writing Content and Attributes

Three properties look similar and are not. textContent reads and writes plain text and is the safe default — it cannot inject markup. innerHTML parses markup, which is convenient for trusted templates and dangerous with user input, because it is a doorway to XSS. innerText reflects rendered text (hidden nodes excluded) but forces layout on every read, so it is slow in loops.

Attributes go through getAttribute/setAttribute, while IDL properties like el.href, el.value, and el.checked give you the live, resolved values. For data-* attributes, one convenience property does the job: el.dataset.userId.

Events: addEventListener, Bubbling, and Delegation

Events flow through three phases: capture (root down to the target), target, then bubble back up. Most listeners run in the bubble phase by default, which enables the single most valuable DOM technique — event delegation. Attach one listener to a container and let it handle events from any current or future child, identified via event.target.closest.

javascript
const list = document.querySelector("#todo-list");

list.addEventListener("click", (event) => {
  const removeBtn = event.target.closest("[data-remove]");
  if (!removeBtn || !list.contains(removeBtn)) return;

  const item = removeBtn.closest("li");
  item.remove();
});

// Items added later work with no extra listeners:
const li = document.createElement("li");
li.innerHTML = 'Buy flour <button type="button" data-remove>x</button>';
list.append(li);

Delegation scales to thousands of rows with one listener and keeps working as content changes. Always guard with closest plus a containment check, so clicks on nested elements inside the button do not double-fire.

Creating, Inserting, and Removing Nodes

The classic trio createElement, appendChild, and removeChild still works, but modern shorthand is shorter: append, prepend, before, after, and remove all exist on elements. cloneNode(true) deep-copies a node for templating. When inserting HTML you authored yourself, insertAdjacentHTML keeps the parent from being rebuilt, unlike assigning to innerHTML.

Text building has a safety net too: document.createTextNode and textContent assignment guarantee no parsing happens. Reach for innerHTML only with static, trusted strings.

Classes, Styles, and Data Attributes

Treat class names as the API between your JavaScript and your CSS. classList.add, remove, toggle, and contains are readable and avoid the footgun of overwriting the entire className string. Direct style writes (el.style.backgroundColor = "red") set inline styles that override stylesheets — fine for computed values like a progress bar's width, wrong for theming.

javascript
function setProgress(bar, percent) {
  const clamped = Math.max(0, Math.min(100, percent));
  bar.style.width = clamped + "%";
  bar.setAttribute("aria-valuenow", String(clamped));
  bar.classList.toggle("is-full", clamped === 100);
}

const bar = document.querySelector("[role='progressbar']");
setProgress(bar, 130);

Data attributes pair well with state: data-state="open" both documents the state for the next developer and gives CSS something to select on.

A Worked Mini-Example: Filterable List

Putting it together — a search box that filters rows as you type, using one listener and no framework:

<div class="filters">
  <label for="q">Filter staff</label>
  <input id="q" type="search" placeholder="Type a name or role">
</div>
<ul id="staff"></ul>
<p id="count" role="status" aria-live="polite"></p>
javascript
const staff = [
  { name: "Asha Rao", role: "Engineer" },
  { name: "Ben Ortiz", role: "Designer" },
  { name: "Chloe Park", role: "Engineer" },
  { name: "Dev Patel", role: "Support" },
];

const listEl = document.querySelector("#staff");
const countEl = document.querySelector("#count");
const inputEl = document.querySelector("#q");

function render(query) {
  const q = query.trim().toLowerCase();
  const hits = staff.filter((person) =>
    person.name.toLowerCase().includes(q) ||
    person.role.toLowerCase().includes(q)
  );

  listEl.replaceChildren(
    ...hits.map((person) => {
      const li = document.createElement("li");
      li.textContent = person.name + " — " + person.role;
      return li;
    })
  );
  countEl.textContent = hits.length + " of " + staff.length + " shown";
}

inputEl.addEventListener("input", () => render(inputEl.value));
render("");

replaceChildren swaps the whole list in one operation, and the role="status" paragraph announces result counts to screen-reader users as they type.

Reflows, Repaints, and Reading-Writing Discipline

Every DOM change has a cost, and the expensive kind is the reflow — a layout recalculation that ripples through affected boxes. Reading a layout property after writing a different one forces the browser to compute geometry mid-frame: the classic performance bug alternates setting an element's inline width and then reading its offset height in a loop, thrashing the layout engine on every iteration. Browsers batch writes that happen together, and they batch reads that happen together, but interleaving the two defeats the batching entirely.

The fix is the read-then-write sandwich. Perform all the reads first — getBoundingClientRect, scrollWidth, clientWidth, computed styles — store the numbers, then perform all the writes: inline styles, class toggles, text updates. Animation code pushes this further by doing per-frame work inside requestAnimationFrame, which schedules just before paint, rather than in a bare setTimeout that may fire after the frame deadline.

javascript
function markClipped(container, items) {
  // Phase 1: read everything first
  const clipped = [];
  for (const item of items) {
    clipped.push(item.scrollWidth > item.clientWidth);
  }

  // Phase 2: write everything second
  for (let i = 0; i < items.length; i += 1) {
    items[i].classList.toggle("is-clipped", clipped[i]);
  }
  container.classList.toggle("has-clipped", clipped.some(Boolean));
}

Beyond batching, prefer bulk APIs. replaceChildren swaps an entire list in one operation; a DocumentFragment accumulates nodes off-DOM before a single insert; the classList methods toggle one flag without rewriting the whole class attribute. For very long lists, virtualization — rendering only the visible window — remains the structural answer, because no amount of batching rescues a thousand-row table that lives entirely in the DOM.

💡Keep one source of truth in the DOM

Before writing a line of update logic, decide which element owns each piece of state. If a row's selected status lives in a class, do not also mirror it in a data attribute and a variable in a closure — pick the class and derive everything else from it. Most hard-to-reproduce DOM bugs are two representations of the same fact drifting apart after an update path that refreshed one and forgot the other. One owner, one update function, and queries that read from that owner keep the tree internally consistent no matter how many features grow on top of it.

Common Mistakes

Attaching a click listener to every row in a long list

Fix: Delegate: one listener on the container, dispatch with event.target.closest.

Using innerHTML with any user-supplied text

Fix: Build nodes with createElement and textContent, which never parse markup.

Expecting querySelectorAll to update as the DOM changes

Fix: It returns a static snapshot — re-query after mutations, or use a live collection deliberately.

Overwriting className to change one class

Fix: Use classList.add, remove, and toggle so other classes survive.

Interview Questions

Q1: What is event bubbling and how does delegation exploit it?

After the target phase, events propagate back up through ancestors. Delegation attaches one listener to an ancestor and inspects event.target with closest() to handle any matching descendant, present or future.

Q2: Difference between textContent and innerHTML?

textContent reads and writes raw text and never parses markup. innerHTML parses the assigned string as HTML, which can execute scripts via injected markup — a common XSS vector.

Q3: Why can querySelectorAll surprise you?

It returns a static NodeList snapshot at call time. Elements added to the DOM afterwards are not in the collection, unlike live HTMLCollections from getElementsByClassName.

Q4: How do you stop a click handler firing on a child click?

Guard with event.target.closest(selector) and verify the container contains the matched node before acting.

Key Takeaways

  • The DOM is the browser's live object tree — references stay valid as the tree changes.
  • querySelector and querySelectorAll accept full CSS selectors; querySelectorAll returns a static snapshot.
  • textContent is the safe content API; innerHTML parses markup and risks XSS with untrusted input.
  • Events bubble — event delegation with closest() gives one listener for all present and future children.
  • Use classList and dataset instead of raw className and getAttribute for readable state handling.
  • replaceChildren, append, and remove make modern DOM updates concise and fast.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement