If you can select it in CSS, you can select it in JavaScript.
Direct answer
document.querySelector(selector) returns the first element matching a CSS selector. document.querySelectorAll(selector) returns a list of all matches. Use #id, .class or tag names as in CSS.
Examples
const title = document.querySelector("h1");
const button = document.querySelector("#save");
const items = document.querySelectorAll(".item");
items.forEach((item) => {
item.classList.add("active");
});
getElementById vs querySelector
getElementById | querySelector | |
|---|---|---|
| Selector | id only | any CSS selector |
| Returns | one element | first match |
| Speed | very slightly faster | flexible |
Common mistakes
- Selecting before the element exists. Put your script at the end of the body or use
defer. - Forgetting
#or.. - Treating
querySelectorAllas an array. It is a list, butforEachworks on it.
Where Teyro fits
Teyro's Interactive Web Pages with JavaScript course turns this into short lessons you can play in a few minutes a day. It has 37 lessons, and you can start free.
The bottom line
Use querySelector for one element and querySelectorAll for many.



