Single logo
  • Courses
  • Articles
  • About
Join for freeJoin free
  1. Blog
  2. /
  3. full-stack-python-architect-mastering-flask-react-ai-first-development
  4. /
  5. querySelectorAll Explained: Selecting Multiple DOM Elements in JavaScript

FULL STACK PYTHON ARCHITECT: FLASK+ REACT + VIBE CODING
Web Development
0 views

querySelectorAll Explained: Selecting Multiple DOM Elements in JavaScript

Learn how querySelectorAll() lets you grab multiple elements from the DOM in one clean line of code, how NodeLists work, and how to loop through them like a pro. Packed with real-world examples you can use today.

A
Author
July 17, 2026

Introduction: Why querySelectorAll Matters

If you've spent any time working with the DOM in JavaScript, you've probably already met document.querySelector() — the handy method that grabs the first element matching a CSS selector. But what happens when you need to grab all the elements that match, not just one? That's where querySelectorAll() comes in.

Whether you're building a to-do list app, highlighting every button on a page, or updating a batch of list items with new styles, querySelectorAll() is one of the most practical and widely-used JavaScript DOM methods you'll ever reach for. In this tutorial, we'll break down exactly how it works, how it differs from querySelector(), and how to confidently manipulate the NodeList it returns.

A Quick Refresher: The DOM Object

Before diving into selectors, it helps to remember what we're actually working with: the DOM (Document Object Model). Every time a browser loads an HTML page, it builds a tree-like structure representing that page — starting with the document, branching into html, head, and body, and continuing down into every nested element and text node.

This tree structure is what makes JavaScript DOM manipulation possible. Once you understand that HTML elements are just nodes in a tree, selecting and modifying them becomes much more intuitive — and that's exactly what selectors like querySelector() and querySelectorAll() are designed to do: help you navigate that tree and grab the nodes you need.

querySelector vs. querySelectorAll: What's the Difference?

Both methods accept a CSS selector as an argument — meaning you can target elements by tag name, class, ID, attribute, or any combination thereof. The key difference lies in what they return:

  • document.querySelector(selector) — returns the first matching element, or null if nothing matches.
  • document.querySelectorAll(selector) — returns all matching elements as a NodeList, even if there's only one match (or none, in which case you get an empty NodeList).

Here's a simple side-by-side comparison:

// Selects only the first paragraph on the page
const firstParagraph = document.querySelector('p');

// Selects every paragraph on the page
const allParagraphs = document.querySelectorAll('p');

console.log(firstParagraph); // A single 

element console.log(allParagraphs); // A NodeList of ALL

elements

Notice that allParagraphs isn't a single element — it's a collection. This distinction is crucial, because it changes how you interact with the result.

Understanding the NodeList

When you call querySelectorAll(), JavaScript doesn't hand you back a single DOM element — it hands you a NodeList. A NodeList looks and behaves a lot like an array (it's indexed, and it has a length property), but it's technically its own data type.

Here's what that looks like in practice:

const listItems = document.querySelectorAll('li');

console.log(listItems.length); // e.g. 5
console.log(listItems[0]);     // the first 
  • element console.log(listItems[1]); // the second
  • element
  • Because NodeLists support modern iteration methods, you can loop through them directly using forEach() — no need to convert them into an array first (in most modern browsers):

    const listItems = document.querySelectorAll('li');
    
    listItems.forEach((item, index) => {
      console.log(`Item ${index}:`, item.textContent);
    });

    This pattern — combining querySelectorAll() with forEach() — is one of the most common techniques you'll use in real-world JavaScript DOM manipulation. If you want a deeper refresher on how forEach works under the hood with callback functions, it's worth revisiting that topic separately, since it pairs so naturally with NodeLists.

    Using CSS Selectors to Target Multiple Elements

    The real power of querySelectorAll() comes from the flexibility of CSS selectors. You're not limited to simple tag names — you can combine classes, IDs, attributes, and even pseudo-classes to precisely target the elements you want.

    Selecting by Class

    const highlightedItems = document.querySelectorAll('.highlight');

    Selecting by Tag and Class Combined

    const activeButtons = document.querySelectorAll('button.active');

    Selecting Nested Elements

    const cardTitles = document.querySelectorAll('.card h2');

    Selecting Multiple Different Elements at Once

    const headings = document.querySelectorAll('h1, h2, h3');

    This last example is particularly useful — by separating selectors with commas, you can grab several different types of elements in a single call, rather than writing multiple separate queries.

    Pro Tip: Copying Selectors from DevTools

    One of the fastest ways to write accurate selectors is to let the browser do the work for you. Open Chrome DevTools, right-click on any element in the Elements panel, and choose Copy → Copy selector. This gives you a precise CSS selector path you can paste directly into querySelectorAll() — no guesswork required.

    This technique is especially valuable when working with complex, deeply nested HTML structures where manually writing a selector might be error-prone. It's a small workflow habit that saves a lot of debugging time down the road.

    Real-World Example: Updating Multiple Elements at Once

    Let's put it all together with a practical example. Imagine you have a list of products on a page, and you want to add a "sale" style to every item with a .product class:

    const products = document.querySelectorAll('.product');
    
    products.forEach((product) => {
      product.style.border = '2px solid red';
      product.style.backgroundColor = '#ffe6e6';
    });

    With just a few lines of code, every matching element on the page is updated — no manual DOM traversal required. This is the everyday power of querySelectorAll(): select once, act on many.

    Common Pitfalls to Avoid

    • Forgetting it's not a live collection: Unlike getElementsByClassName() or getElementsByTagName(), which return live HTMLCollections that update automatically, a NodeList from querySelectorAll() is static. If you add new matching elements to the page afterward, you'll need to query again.
    • Assuming it's a true array: While NodeLists support forEach(), they don't have every array method (like map() or filter()) by default. If you need those, convert it first: Array.from(nodeList).
    • Confusing querySelector and querySelectorAll: Remember — one returns a single element, the other returns a collection. Mixing them up is a common source of bugs like "Cannot read property 'style' of undefined."

    Featured Video

    [Course video embed goes here — watch the full lecture on querySelectorAll() and DOM selectors in action.]

    Where This Fits Into the Bigger Picture

    Mastering querySelectorAll() is just one piece of a much larger DOM manipulation toolkit. In the FULL STACK PYTHON ARCHITECT: Flask + React + Vibe Coding course, this lecture builds directly on earlier lessons covering querySelector(), getElementById(), getElementsByClassName(), and getElementsByTagName() — giving you a complete, hands-on understanding of how to traverse and manipulate the DOM before moving into more advanced JavaScript concepts like functions, this, and array methods like map() and forEach().

    Understanding these fundamentals thoroughly pays off later when you start building dynamic, interactive front-ends — including when you transition into frameworks like React, where much of this DOM logic is abstracted but still important to understand at a foundational level.

    Conclusion: Key Takeaways

    • querySelector() returns the first matching element; querySelectorAll() returns all matches as a NodeList.
    • A NodeList behaves like an array in many ways (indexed, has length, supports forEach()) but isn't a true array.
    • You can combine CSS selectors — classes, tags, IDs, and nested paths — to precisely target multiple elements at once.
    • Use browser DevTools to quickly copy accurate selectors instead of writing them manually.
    • querySelectorAll() combined with forEach() is one of the most practical patterns for real-world DOM manipulation.

    Once you're comfortable with querySelectorAll(), you'll find it becomes second nature in almost every JavaScript project — from simple landing pages to complex full-stack applications. If you'd like to go deeper into DOM selectors, functions, and modern JavaScript array methods with guided, hands-on lessons, this topic is covered in detail inside the full course.

    Tags:
    querySelectorAll JavaScript
    NodeList JavaScript
    select multiple elements JavaScript
    JavaScript DOM methods
    querySelector vs querySelectorAll
    Share Article

    Back to All Articles

    Single logo

    Empowering Education, One Course at a Time

    About
    About usContact usFAQs
    Legal
    Terms of ServicePrivacy Policy

    © 2026 StudyEasy Organization. All rights reserved.