0Pricing
JavaScript Academy · Lesson

Selecting Elements with querySelector

Find elements using CSS selectors.

Selecting Elements with querySelector is a free JavaScript Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Meet querySelector

querySelector returns the first element that matches a CSS selector, or null if nothing matches. It lives on document and on every element.

const title = document.querySelector("h1");
console.log(title.textContent);

Any CSS Selector Works

The power of querySelector is that it accepts the same selectors you use in CSS: tags, classes, ids, attributes, and combinations.

document.querySelector("#main");      // by id
document.querySelector(".card");      // by class
document.querySelector("input[type=email]"); // by attribute

querySelectorAll

querySelectorAll returns all matching elements as a static NodeList. Even with zero matches it returns an empty list (never null).

const cards = document.querySelectorAll(".card");
console.log(cards.length);

Looping Over Results

A NodeList from querySelectorAll supports forEach directly, which makes iteration clean.

const items = document.querySelectorAll("li");
items.forEach((li) => {
  console.log(li.textContent);
});

Descendant Selectors

You can target nested elements with a space (descendant) just like CSS. This finds every .price inside a .product.

const prices = document.querySelectorAll(".product .price");

Combining Classes

Chaining classes with no space means an element must have all of them. Here we match buttons that are both primary and large.

const btn = document.querySelector("button.primary.large");

Scoped Queries

Calling querySelector on an element (not document) searches only inside that element. This keeps searches local and fast.

const form = document.querySelector("#signup");
const emailField = form.querySelector("input[name=email]");

Pseudo-classes

Structural pseudo-classes like :first-child and :nth-of-type work too.

document.querySelector("li:first-child");
document.querySelectorAll("tr:nth-of-type(even)");

Handling No Match

Because querySelector can return null, guard before using the result to avoid a TypeError.

const banner = document.querySelector(".banner");
if (banner) {
  banner.classList.add("hidden");
}

Attribute Selectors

Attribute selectors let you match on data attributes, which is great for hooking into elements without relying on classes.

const widget = document.querySelector("[data-role=widget]");
const openTabs = document.querySelectorAll("[aria-expanded=true]");

querySelector vs Older APIs

querySelector is more flexible than getElementById because it accepts any selector, but id lookups are still slightly faster. Use the right tool for the job.

document.querySelector("#nav");        // flexible
document.getElementById("nav");        // fastest for ids

Quick Check

Test your understanding of selectors.

Recap

You learned that querySelector returns the first match (or null) and querySelectorAll returns a static NodeList of all matches. Both accept full CSS selectors and can be scoped to a parent element. Always guard against null when using querySelector.

Frequently asked questions

Is the “Selecting Elements with querySelector” lesson free?

Yes — the full text of “Selecting Elements with querySelector” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Selecting Elements with querySelector”?

Find elements using CSS selectors. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Selecting Elements with querySelector” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Selecting Elements with querySelector
  2. getElementById and getElementsByClassName
  3. Traversing Parents, Children and Siblings
  4. NodeList vs HTMLCollection
← Back to JavaScript Academy