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
querySelectorreturnsnullif nothing matches — always guard against that before using the result (heading?.textContent, or an explicitif).querySelectorAllreturns a staticNodeList, a snapshot at the time of the call — it does not update automatically if matching elements are added or removed later.textContentnever parses its input as HTML, unlikeinnerHTML— 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 theclassattribute string.
Common mistakes
- Calling a method on the result of
querySelectorwithout checking it isn’tnullfirst. - Using
innerHTMLfor plain text updates whentextContentis 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.