Finding elements on the page
Before you can change anything on a page, you need to find it. JavaScript gives you two main methods — both use CSS selectors, so if you know CSS, you already know how to use them.document.querySelector()
Returns the first element that matches a CSS selector:querySelector returns null — not an error.
document.querySelectorAll()
Returns all matching elements as aNodeList:
Iterating over results
querySelectorAll returns a NodeList, not an array. It has .forEach() but not .map(), .filter(), etc. Spread it into an array with [...nodeList] when you need array methods.Common CSS selectors
You use the same selectors as CSS. Here’s a quick reference:Practical examples
Older methods (still common)
You’ll see these in older code and tutorials:- Modern (use this)
- Older (you'll still see)
querySelector / querySelectorAll are the modern standard. They’re more flexible (any CSS selector) and more consistent (querySelectorAll always returns a static NodeList).
Scope your selectors
You can callquerySelector on any element, not just document:
Common mistakes
Selecting elements before they exist
Selecting elements before they exist
Forgetting the dot or hash in selectors
Forgetting the dot or hash in selectors
Treating querySelectorAll like an array
Treating querySelectorAll like an array
What’s next?
You can find elements. Now let’s change them — text, styles, classes, and attributes.Modifying elements
Change text, styles, attributes, and classes