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.
What is document?
Section titled “What is document?”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.
Grabbing an element with querySelector
Section titled “Grabbing an element with querySelector”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> tagIf you know how to write a CSS selector, you already know how to select elements in JavaScript. The syntax is identical.
Reading and changing text
Section titled “Reading and changing text”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 textvar currentText = heading.textContent;
// Change the textheading.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.
Selector quick reference
Section titled “Selector quick reference”| What you want to select | Selector syntax |
|---|---|
| An element with a class | .className |
| An element with an id | #idName |
| A tag type | button, 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.