How can I use querySelectorAll() to select elements by class name?
Answers:
You can use the
querySelectorAll()
method in JavaScript to select elements by class name. ThequerySelectorAll()
method takes a CSS selector string as an argument and returns a static NodeList of elements that match the selector.To select elements by class name, you'll need to prefix the class with a dot (
.
). Here's the basic syntax:const elements = document.querySelectorAll('.className');
In this code:
- Replace
className
with the actual name of the class you want to select. - The variable
elements
will hold a NodeList of all elements in the document that have the specified class.
Example
Here’s a simple example that demonstrates how to use
querySelectorAll()
to select elements by class name:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>querySelectorAll Example</title> </head> <body> <div class="example">Item 1</div> <div class="example">Item 2</div> <div class="example">Item 3</div> <div class="other">Item 4</div> <script> // Select all elements with the class name 'example' const elements = document.querySelectorAll('.example'); // Iterate over the NodeList and log the text content of each element elements.forEach(element => { console.log(element.textContent); }); </script> </body> </html>
Explanation:
- In the example, there are multiple
<div>
elements with the class nameexample
. - The
document.querySelectorAll('.example')
selects all elements with that class. - The script then iterates over the NodeList using
forEach()
to log the text content of each selected element.
Notes:
- The
NodeList
returned byquerySelectorAll()
is static, meaning it will not automatically update if the DOM changes (e.g., if elements are added or removed after the selection). - You can also combine selectors. For example,
document.querySelectorAll('div.example')
will select only<div>
elements with the classexample
.
- Replace
Related Questions:
-
What are some common use cases for querySelectorAll()?
-
How does querySelectorAll() differ from getElementsByClassName()?
-
What is the syntax for querySelectorAll() in JavaScript?
-
How do I iterate through elements selected by querySelectorAll()?
-
Can I use querySelectorAll() to select elements by attribute?
-
How do I use querySelectorAll() to select multiple classes?
-
What is the performance of querySelectorAll() compared to other selection methods?
-
Can I use querySelectorAll() to select child elements?
-
How can querySelectorAll() be used in combination with querySelector()?
-
How do I filter results when using querySelectorAll()?