How do I apply a style to all elements selected by querySelectorAll()?
Answers:
To apply a style to all elements selected by
querySelectorAll()
, you can loop through the NodeList returned byquerySelectorAll()
and set the desired styles using JavaScript. Here's a simple example of how to do that:Example:
Suppose you want to apply a background color and a text color to all
<p>
elements on your webpage.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Style Elements Example</title> <style> /* Default styles for paragraphs */ p { font-size: 16px; margin: 10px 0; } </style> </head> <body> <p>This is the first paragraph.</p> <p>This is the second paragraph.</p> <p>This is the third paragraph.</p> <script> // Select all <p> elements const paragraphs = document.querySelectorAll('p'); // Loop through the NodeList and apply styles paragraphs.forEach(function(paragraph) { paragraph.style.backgroundColor = 'lightblue'; // Set background color paragraph.style.color = 'darkblue'; // Set text color paragraph.style.padding = '10px'; // Set padding }); </script> </body> </html>
Explanation:
- Select Elements: Use
document.querySelectorAll('p')
to select all<p>
elements on the page, which returns a NodeList. - Loop through Elements: Use the
forEach
method to loop through each element in the NodeList. - Apply Styles: In the callback function, you can use the
style
property of each element to apply your desired styles.
Troubleshooting:
- Make sure that your
<script>
tag is placed at the end of the body, or wrap your JavaScript in an event listener forDOMContentLoaded
to ensure the DOM is fully loaded before executing the script. - Adjust the selectors in
querySelectorAll()
to target the specific elements you want to style.
- Select Elements: Use