What is the syntax for querySelectorAll() in JavaScript?
Answers:
The
querySelectorAll()
method in JavaScript is used to select all elements in the DOM that match a specified CSS selector. It returns a NodeList, which is a collection of the selected elements.Syntax:
document.querySelectorAll(selector);
Parameters:
- selector: A string containing one or more CSS selectors separated by commas. This string specifies the elements to select.
Example:
// Select all <p> elements in the document const paragraphs = document.querySelectorAll('p'); // Select all elements with the class "active" const activeElements = document.querySelectorAll('.active'); // Select all <div> elements that are direct children of an element with the ID "container" const containerDivs = document.querySelectorAll('#container > div'); // Select all elements matching multiple selectors const mixedElements = document.querySelectorAll('div.active, p.special');
Usage:
- The resulting NodeList can be iterated over using methods like
forEach
or by converting it to an array. - Note that the NodeList returned is "live" when using some methods but not when using
querySelectorAll()
. So the NodeList doesn't update if the document changes after the selection.
Example with Iteration:
const items = document.querySelectorAll('.item'); items.forEach(item => { console.log(item.textContent); // Logs the text content of each item });
In summary,
querySelectorAll()
is a powerful and flexible way to select multiple elements based on CSS selectors in JavaScript.
Related Questions:
-
What is the difference between querySelector() and querySelectorAll()?
-
What are the performance implications of using querySelectorAll()?
-
What happens if no elements match the selector in querySelectorAll()?
-
How do you use querySelectorAll() to select multiple elements?
-
How can you filter elements selected by querySelectorAll()?
-
Can querySelectorAll() be used with class names?
-
Can querySelectorAll() select elements by attribute values?
-
What kind of selectors can be used with querySelectorAll()?
-
How do you convert the NodeList from querySelectorAll() to an array?
-
Can querySelectorAll() be used on a specific element rather than the whole document?