How do I select multiple elements using querySelectorAll()?
Answers:
The
querySelectorAll()
method in JavaScript is used to select multiple elements from the DOM based on a specified CSS selector. The method returns a NodeList of all elements that match the specified selector.Syntax
const elements = document.querySelectorAll('selector');
Steps to use
querySelectorAll()
-
Define Your Selector: Create your CSS selector string. This can be any valid CSS selector, including class selectors, ID selectors, attribute selectors, and more.
-
Call the Method: Pass the selector as an argument to
querySelectorAll()
, which is called on thedocument
object or a specific element. -
Use the Result: The result is a NodeList, which can be iterated over using methods like
forEach
, or can be converted to an array if you need to use array methods.
Examples
-
Selecting all paragraphs:
const paragraphs = document.querySelectorAll('p'); paragraphs.forEach(paragraph => { console.log(paragraph.textContent); });
-
Selecting all elements with a specific class:
const items = document.querySelectorAll('.item'); items.forEach(item => { item.style.color = 'blue'; });
-
Selecting by multiple classes:
const specialItems = document.querySelectorAll('.item.special'); specialItems.forEach(item => { item.classList.add('highlight'); });
-
Selecting elements using IDs (note the use of
#
for IDs):const element = document.querySelectorAll('#myId'); console.log(element); // Returns a NodeList, typically contains one element
-
Using attribute selectors:
const inputs = document.querySelectorAll('input[type="text"]'); inputs.forEach(input => { input.value = 'Hello'; });
Note
-
The
NodeList
returned byquerySelectorAll()
is not an array, but you can convert it to an array if needed:const nodesArray = Array.from(document.querySelectorAll('div')); // or const nodesArray = [...document.querySelectorAll('div')];
-
Remember that
querySelectorAll()
returns elements that match the selector at the time the method is called. If the DOM changes later (e.g., elements are added or removed), the NodeList will not be updated.
Using
querySelectorAll()
is a powerful way to work with multiple elements in the DOM efficiently.-
Related Questions:
-
What is the difference between querySelector and querySelectorAll?
-
What are the performance considerations when using querySelectorAll?
-
What is the return type of querySelectorAll?
-
How do I loop through elements selected by querySelectorAll?
-
How can I select elements with a specific class using querySelectorAll?
-
Can querySelectorAll select elements by multiple selectors?
-
How do I select child elements using querySelectorAll?
-
Can I use querySelectorAll with pseudo-elements?
-
How does querySelectorAll handle duplicate class names?
-
How can I filter elements selected by querySelectorAll?