- Welcome
-
Examples
- addEventListener()
- Buttons
- Data Attribute
- document.
querySelectorAll()
- forEach()
- Multiple Classes
- to array -
Errors
- Failed to execute 'querySelectorAll' on 'document'
- Advanced
- querySelectorAll() vs querySelector()
- Performance
- Questions
- Troubleshooting
External
Examples
The querySelectorAll() function is a powerful tool in JavaScript that allows you to select one or more elements on a webpage based on their CSS selector. This function returns a NodeList of all the elements that match the specified selector, which you can then manipulate in various ways.
Here are a few examples of how you can use querySelectorAll() in different scenarios:
Selecting elements with a specific class
To select all elements on a page with a given class, you can pass the class name to querySelectorAll() as a CSS selector. For example, to select all elements with the class "highlight", you could use the following code:
const highlights = document.querySelectorAll('.highlight');
This will return a NodeList containing all the elements with the class "highlight", which you can then manipulate using JavaScript.
Applying styles to selected elements
Once you have selected one or more elements using querySelectorAll(), you can apply styles to them using the style property. For example, to set the font size of all elements with the class "highlight" to 24 pixels, you could use the following code:
const highlights = document.querySelectorAll('.highlight');
highlights.forEach((highlight) => {
highlight.style.fontSize = '24px';
});
This code uses the forEach() method to iterate over the NodeList and apply the desired styles to each element.
Adding event listeners to selected elements
In addition to applying styles, you can also add event listeners to the elements you select using querySelectorAll(). This allows you to respond to user interactions, such as clicks or hover events, on the selected elements. For example, to add a click event listener to all elements with the class "button", you could use the following code:
const buttons = document.querySelectorAll('.button');
buttons.forEach((button) => {
button.addEventListener('click', (event) => {
// Your event handling code here...
});
});
This code uses the addEventListener() method to attach a click event listener to each element in the NodeList. When a user clicks on one of these elements, the specified event handling code will be executed.
These are just a few examples of how you can use the querySelectorAll() function in your web development projects. With this powerful function, you can easily select and manipulate elements on a page, giving you greater control over the user experience and the behavior of your web applications.