JavaScript lesson · 21 min

JavaScript querySelector and querySelectorAll

Find one element or many elements with CSS-style DOM selectors.

Code runs locally in your browser

What you will practice

  • Use querySelector for one matching element.
  • Use querySelectorAll for a list of matching elements.
  • Use classes and data attributes as reliable selectors.

What this means

`querySelector` finds the first element that matches a CSS selector.

`querySelectorAll` finds all matching elements and returns a list-like collection.

Good selectors make your JavaScript easier to maintain. A class or `data-*` attribute is often clearer than depending on exact tag order.

If this is your first time seeing this

Selectors are search rules for finding elements on a page.

`querySelector` gives one match; `querySelectorAll` gives all matches.

Mini glossary

Selector
A CSS-style rule used to find elements.
querySelector
Finds the first element that matches a selector.
querySelectorAll
Finds every element that matches a selector.

Example from everyday life

Using selectors is like finding a book in a library. You can ask for the first book with a blue sticker, or you can ask for every book on the shelf with the `JavaScript` label.

How it works step by step

  1. The example creates a list of tools with `data-kind` attributes.
  2. `querySelector('[data-kind="tool"]')` returns the first tool item.
  3. `querySelectorAll('[data-kind="tool"]')` returns every matching tool item.
  4. The code prints the first matching item and the total count.

Where you will use this

  • A menu script finds all navigation links and marks the current page.
  • A checklist script finds every checked item before saving.
  • A product grid finds all cards with a selected category.

Before you run the code

Selectors use the same basic syntax as CSS: `h1` for a tag, `.intro` for a class, `#save` for an id, and `[data-kind="tool"]` for an attribute.

When you need one element, use `querySelector`. When you need many, use `querySelectorAll` and then loop over the results.

Common beginner mistakes

  • Using `querySelector` when you expected many elements.
  • Writing a selector that is too broad and matches the wrong element.
  • Depending on fragile tag order instead of stable classes or data attributes.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingFinds the first matching tool
WaitingCounts all matching tools

Code runs locally in an isolated sandboxed browser frame with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Add a third `data-kind="tool"` item and check the count.
  • Change the selector to `[data-kind="lesson"]`.
  • Try selecting the `ul` element and printing its full text.