LESSON 24

Selecting Elements

Learning objective: Find elements on the page to work with them.

Understand

To change an element, you first select it.

document.querySelector returns the first element matching a CSS selector, and querySelectorAll returns all matches. Once selected, you can read or change the element. Give elements ids or classes to target them.

Analogy: Selecting is like pointing at exactly the object you want before picking it up.

See It in Action

Selecting by id and class:

const title = document.querySelector("#title");
const items = document.querySelectorAll(".item");
How it works: #title grabs the element with that id, and .item collects every element with that class.

Try It Yourself

  1. Select an element by its id.
  2. Select several by class.
  3. Log the selected element to confirm.

Quick Quiz

What does querySelector return?

Challenge

Select a heading and log it to the console.

Success condition: Your selected element appears correctly in the console.