querySelectorAll
A JavaScript method that returns all elements in the document matching a specified CSS selector as a static NodeList.
Overview
querySelectorAll() is a powerful DOM method that allows you to select multiple elements using CSS selectors. Unlike querySelector() which returns only the first match, querySelectorAll() returns all matching elements. The returned NodeList is static, meaning it doesn't update if the DOM changes after the query.
Example
javascript// Select all paragraphs const paragraphs = document.querySelectorAll('p'); // Select all elements with a class const buttons = document.querySelectorAll('.button'); // Complex CSS selectors const inputs = document.querySelectorAll('input[type="text"]'); const items = document.querySelectorAll('.list > .item'); const links = document.querySelectorAll('nav a:not(.active)'); // Multiple selectors const elements = document.querySelectorAll('h1, h2, h3'); // Convert NodeList to Array for array methods const buttonArray = Array.from(buttons); // or const buttonArray2 = [...buttons]; // Iterate over results paragraphs.forEach(p => { p.style.color = 'blue'; }); // Using modern array methods const textContents = Array.from(paragraphs).map(p => p.textContent); // Check if elements exist const items = document.querySelectorAll('.item'); if (items.length > 0) { console.log('Found items!'); } // Scoped selection (search within an element) const container = document.querySelector('.container'); const childElements = container.querySelectorAll('.child'); // Practical examples // Add event listener to all buttons document.querySelectorAll('button').forEach(button => { button.addEventListener('click', handleClick); }); // Toggle class on all elements document.querySelectorAll('.toggle').forEach(el => { el.classList.toggle('active'); }); // Get data from all form inputs const values = Array.from( document.querySelectorAll('input') ).map(input => input.value);
Key Points
- Returns all matching elements as NodeList
- Uses CSS selector syntax
- Returns static NodeList (doesn't auto-update)
- Returns empty NodeList if no matches
- Can be called on any element, not just document
Learn More
- Query Selector - querySelector method
- DOM - Document Object Model
- Document - Document object
- MDN: querySelectorAll