30 min·intermediate

Lesson 2

Selecting & changing elements

Build a practical mental model for selecting & changing elements and use it in working JavaScript.

By the end, you will be able to…

  • Explain selecting & changing elements in your own words
  • Use selecting & changing elements in a small program
  • Recognize and debug a common failure mode

Build the mental model

querySelector finds the first element matching a CSS selector (or null if none match); once you have a reference, you can change its text, attributes, and classes directly.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: The <h1> text changes and gains a CSS class

Why this matters

Selecting narrowly and defensively (checking for null) prevents an entire class of 'Cannot read properties of null' runtime crashes.

Real-world example

A 'mark as read' button toggling a CSS class on a notification is this exact select-then-mutate pattern.

Common mistakes

  • Not checking whether querySelector returned null before using the result
  • Using innerHTML with untrusted input, opening an XSS vulnerability
  • Selecting too broadly (a whole page) instead of narrowing to what you need

Try it yourself

Challenge

Simulate updating an element object's text safely, only if it exists.

Practice

Knowledge check

What does document.querySelector return when nothing matches the selector?

Summary

Select narrowly with querySelector, guard against null, and prefer textContent over innerHTML for plain text.