Episode 4 of 18

The Query Selector

Use querySelector and querySelectorAll — select elements with CSS selectors for maximum flexibility and precision.

The Query Selector

querySelector and querySelectorAll let you select elements using CSS selectors — the same selectors you use in your stylesheets. They are the most versatile selection methods available.

querySelector

// Select the FIRST match
var title = document.querySelector('#page-title');   // by ID
var firstMsg = document.querySelector('.message');    // first .message
var firstP = document.querySelector('p');             // first <p>
var nested = document.querySelector('div.wrapper p'); // nested selector
var attr = document.querySelector('[data-type="primary"]'); // attribute

querySelector returns the first element that matches the CSS selector, or null if nothing matches.

querySelectorAll

// Select ALL matches
var messages = document.querySelectorAll('.message');
console.log(messages);         // NodeList(3)
console.log(messages.length);  // 3

// NodeList supports forEach directly!
messages.forEach(function(msg) {
    console.log(msg.textContent);
});

querySelectorAll returns a NodeList of all matching elements. Unlike HTMLCollections, NodeLists support forEach directly.

NodeList vs HTMLCollection

FeatureNodeList (querySelectorAll)HTMLCollection (getElementsBy...)
forEach supportYesNo (needs Array.from)
Live updatesNo (static snapshot)Yes (updates with DOM)
Selector powerFull CSS selectorsClass or tag name only

Complex Selectors

// Pseudo-selectors
var even = document.querySelectorAll('li:nth-child(even)');
var last = document.querySelector('ul li:last-child');

// Multiple selectors
var headings = document.querySelectorAll('h1, h2, h3');

// Nested selectors
var links = document.querySelectorAll('nav a.active');

Key Takeaways

  • querySelector returns the first match; querySelectorAll returns all matches
  • Both accept any valid CSS selector — IDs, classes, tags, attributes, pseudo-selectors
  • querySelectorAll returns a static NodeList that supports forEach
  • These are the most commonly used selection methods in modern JavaScript