DOM
Selecting Elements
getElementById, querySelector, querySelectorAll.
1. Explanation
Use getElementById for a unique ID. querySelector accepts any CSS selector and returns the first match. querySelectorAll returns a NodeList of all matches — iterate with forEach or for...of. Prefer querySelector in modern code.
2. Example
Try it yourself
Console
Click Run to see output.
3. Expected output
output
(updates the page visually)4. Common mistakes
- ✗Forgetting that querySelectorAll returns a NodeList, not an Array (no .map directly — use [...nodes])
- ✗Selecting before the element is in the DOM
- ✗Using IDs that contain spaces or start with a number — invalid
5. Practice questions
- Select an element and change its background colour
- Get all <p> tags and underline them
- Use querySelector to grab an element with a specific data attribute