Skip to content

Selecting Elements

Think of a webpage like a Figma file. Every heading, button, image, and paragraph is a layer sitting inside the canvas. Before you can style or animate anything in Figma, you first have to click that layer to select it. JavaScript works exactly the same way — before you can change something on the page, you have to select it.

document is JavaScript’s name for the entire page. It represents the whole HTML file that the browser has loaded. Any time you want to reach into the page and interact with it, you start from document.

document.querySelector() is the main tool for selecting elements. You pass it a CSS selector — the same kind you already write in your stylesheets — and it returns the first matching element it finds.

document.querySelector('.card') // selects the first element with class "card"
document.querySelector('#title') // selects the element with id "title"
document.querySelector('button') // selects the first <button> tag

If you know how to write a CSS selector, you already know how to select elements in JavaScript. The syntax is identical.

Once you have a reference to an element, you can read or change its text content using the .textContent property.

var heading = document.querySelector('h1');
// Read the current text
var currentText = heading.textContent;
// Change the text
heading.textContent = 'New heading text';

Assigning a new value to .textContent immediately updates what the visitor sees — no page reload required.

The example above selects the #changeBtn button and the #headline heading. When the button is clicked, the script updates the heading’s text. Everything relies on querySelector doing the selecting first.

What you want to selectSelector syntax
An element with a class.className
An element with an id#idName
A tag typebutton, h2, p
A nested element.card h2

Any valid CSS selector works inside querySelector. If you can target it in a stylesheet, you can grab it in JavaScript.

What does `document.querySelector('#title')` select?
Which selector finds an element by class name?
What property lets you read or change the text inside an element?