Selecting and Updating DOM Elements

querySelector/querySelectorAll to find elements, and textContent/classList/setAttribute to read and update them safely.

                document.querySelector(selector) / element.textContent = text
              

Purpose

document.querySelector/querySelectorAll find one or all elements matching a CSS selector. textContent, classList, and setAttribute/getAttribute read and update an element’s content, CSS classes, and attributes.

Syntax

const heading = document.querySelector('h1'); // first match, or null
const items = document.querySelectorAll('.item'); // all matches, as a static NodeList

heading.textContent = 'Updated title'; // sets text safely — never parsed as HTML
heading.classList.add('highlighted');
heading.classList.toggle('active');
heading.setAttribute('data-status', 'active');
console.log(heading.getAttribute('data-status')); // "active"

Behavior notes

  • querySelector returns null if nothing matches — always guard against that before using the result (heading?.textContent, or an explicit if).
  • querySelectorAll returns a static NodeList, a snapshot at the time of the call — it does not update automatically if matching elements are added or removed later.
  • textContent never parses its input as HTML, unlike innerHTML — see the XSS note in The Browser and the DOM for why that distinction matters with untrusted text.
  • classList (add, remove, toggle, contains) is the standard way to manage CSS classes, clearer than manually editing the class attribute string.

Common mistakes

  • Calling a method on the result of querySelector without checking it isn’t null first.
  • Using innerHTML for plain text updates when textContent is both safer and slightly faster, since it skips HTML parsing entirely.

Runtime notes

Part of the DOM standard — browser-only; none of these APIs exist in Node without an added library.

Taught in these lessons

Related reference