return elements that match specified CSS selector(s)

How can I apply styles to multiple elements selected by querySelectorAll()?

Answers:

  • You can apply styles to multiple elements selected using querySelectorAll() by iterating over the returned NodeList and applying the styles to each element individually. Here's a simple example of how to do this using JavaScript:

    Example HTML:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Apply Styles Example</title>
        <style>
            .my-class {
                color: blue;
                font-size: 20px;
            }
        </style>
    </head>
    <body>
        <div class="my-class">Element 1</div>
        <div class="my-class">Element 2</div>
        <div class="my-class">Element 3</div>
        <button id="styleButton">Apply Styles</button>
    
        <script src="script.js"></script>
    </body>
    </html>
    

    JavaScript (script.js):

    document.getElementById('styleButton').addEventListener('click', function() {
        // Select all elements with the class 'my-class'
        const elements = document.querySelectorAll('.my-class');
    
        // Iterate through the NodeList and apply styles
        elements.forEach(function(element) {
            element.style.color = 'red'; // Change text color to red
            element.style.backgroundColor = 'yellow'; // Change background color to yellow
            element.style.fontSize = '25px'; // Change font size to 25px
            // Add more styles as needed
        });
    });
    

    Explanation:

    1. Selecting Elements: The querySelectorAll() method is used to select all elements that match a specific CSS selector. In this case, '.my-class' selects all elements with the class my-class.

    2. Iterating Over NodeList: The result of querySelectorAll() is a NodeList. You can use the forEach method to iterate over each element in the NodeList.

    3. Applying Styles: Inside the loop, you can access the style property of each element and set various CSS properties such as color, backgroundColor, and fontSize.

    4. Interactive Example: The example includes a button that, when clicked, applies the styles to the selected elements.

    This is a straightforward approach to style multiple elements dynamically using JavaScript. You can expand it further by adding conditions or more complex styling logic.

Related Questions: