0Pricing
Frontend Academy · Lesson

querySelector and querySelectorAll

Find single and multiple elements using CSS selector strings and understand the difference between NodeList and HTMLCollection.

querySelector and querySelectorAll is a free Frontend 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 Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is the DOM?

The Document Object Model is a tree of JavaScript objects that represents the HTML structure. JavaScript interacts with the DOM to read, modify, add, and remove elements — making web pages dynamic.

getElementById

The classic selector. document.getElementById('myId') returns the element with that id, or null if not found. It's fast but only works with IDs.

const header = document.getElementById('site-header');
if (header) {
  header.style.backgroundColor = 'navy';
}

querySelector — Single Element

document.querySelector(cssSelector) returns the first element that matches any CSS selector. Returns null if none found. More flexible than getElementById.

const btn = document.querySelector('.btn-primary');
const input = document.querySelector('input[type="email"]');
const hero = document.querySelector('#hero h1');

querySelectorAll — Multiple Elements

document.querySelectorAll(cssSelector) returns a static NodeList of all matching elements. It's not a live array — you must iterate it. Use Array.from() or spread to use array methods.

const cards = document.querySelectorAll('.card');
cards.forEach(card => card.classList.add('loaded'));

// Convert to array for array methods:
const hrefs = Array.from(document.querySelectorAll('a')).map(a => a.href);

Scoped Queries

You can call querySelector on any element to search only within that subtree — not the entire document. This is more efficient and prevents accidentally selecting elements from other parts of the page.

const nav = document.querySelector('#main-nav');
const links = nav.querySelectorAll('a'); // only links inside #main-nav

NodeList vs HTMLCollection

NodeList (from querySelectorAll) is static — it reflects the DOM at query time. HTMLCollection (from getElementsByClassName etc.) is live — it updates automatically as the DOM changes. Both are array-like but not arrays.

Traversing the DOM

From any element you can navigate: element.parentElement, element.children, element.firstElementChild, element.lastElementChild, element.nextElementSibling, element.previousElementSibling.

const list = document.querySelector('ul');
console.log(list.children.length);       // number of li elements
console.log(list.firstElementChild);     // first li
console.log(list.parentElement);         // ul's parent

Checking If an Element Exists

Always check that querySelector didn't return null before using the result, especially for elements that may not be present on every page.

const modal = document.querySelector('.modal');
if (modal) {
  // safe to use modal here
  modal.classList.add('open');
}

matches() and closest()

element.matches(selector) returns true if the element matches the selector. element.closest(selector) walks up the DOM tree and returns the first ancestor matching the selector, or null.

const item = document.querySelector('.list-item');
console.log(item.matches('.active'));     // false

// Event delegation: find the clicked card
document.addEventListener('click', (e) => {
  const card = e.target.closest('.card');
  if (card) card.classList.toggle('selected');
});

contains()

parentElement.contains(childElement) returns true if the child is inside the parent (or is the parent itself). Useful for checking if a click happened outside a modal or dropdown.

document.addEventListener('click', (e) => {
  const menu = document.querySelector('.dropdown-menu');
  if (!menu.contains(e.target)) {
    menu.hidden = true; // clicked outside
  }
});

Performance: Minimise DOM Queries

DOM queries are not free. Cache the result in a variable instead of calling querySelector repeatedly. In loops, batch DOM reads together and DOM writes together to avoid layout thrashing.

// Bad — queries DOM in every iteration:
for (let i = 0; i < 100; i++) {
  document.querySelector('#counter').textContent = i;
}

// Good — cache the element:
const counter = document.querySelector('#counter');
for (let i = 0; i < 100; i++) counter.textContent = i;

Quick Check

Which method returns a static NodeList of all matching elements?

Recap: Selecting DOM Elements

querySelector returns the first match. querySelectorAll returns all matches as a static NodeList. Scope queries to a subtree for efficiency. Cache query results. Use closest() for event delegation. Always null-check before using a queried element.

Frequently asked questions

Is the “querySelector and querySelectorAll” lesson free?

Yes — the full text of “querySelector and querySelectorAll” is free to read here on the web, and the Frontend 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 Frontend Academy course, upgrade to CoddyKit PRO.

What will I learn in “querySelector and querySelectorAll”?

Find single and multiple elements using CSS selector strings and understand the difference between NodeList and HTMLCollection. You practise Frontend 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 Frontend Academy?

No prior experience is required. Frontend 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 “querySelector and querySelectorAll” 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 Frontend Academy lesson?

Yes. Every Frontend 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. querySelector and querySelectorAll
  2. addEventListener and Event Object
  3. Changing Content: textContent innerHTML classList
  4. Creating and Appending Elements
← Back to Frontend Academy