All tutorials
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

  1. Select an element and change its background colour
  2. Get all <p> tags and underline them
  3. Use querySelector to grab an element with a specific data attribute
→ Try more practice problems