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
| Feature | NodeList (querySelectorAll) | HTMLCollection (getElementsBy...) |
|---|---|---|
| forEach support | Yes | No (needs Array.from) |
| Live updates | No (static snapshot) | Yes (updates with DOM) |
| Selector power | Full CSS selectors | Class 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
querySelectorreturns the first match;querySelectorAllreturns all matches- Both accept any valid CSS selector — IDs, classes, tags, attributes, pseudo-selectors
querySelectorAllreturns a static NodeList that supportsforEach- These are the most commonly used selection methods in modern JavaScript