Skip to content
Justice Tech School

Selecting Elements

getElementById finds one element by id. querySelector takes any CSS selector and returns the first match, while querySelectorAll returns all matches as a list you can loop over.

Example
const box = document.getElementById("demo");
box.innerHTML = "<p class=\"item\">One</p><p class=\"item\">Two</p><p>Three</p>";
const first = document.querySelector(".item");
first.style.color = "crimson";
const items = document.querySelectorAll(".item");
console.log(items.length);
items.forEach((el) => (el.style.fontWeight = "bold"));

Exercise

Select every paragraph.

document.("p")

Quiz Test

What does querySelector return?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.