return elements that match specified CSS selector(s)

Can I update the HTML content of elements selected by querySelectorAll()?

Answers:

  • Yes, you can update the HTML content of elements selected by querySelectorAll() in JavaScript. This method returns a NodeList of elements that match the specified CSS selectors. You can then use a loop to iterate over each of these elements and update their HTML content.

    Here’s an example of how you can do this:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Update HTML Content Example</title>
    </head>
    <body>
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
        <div class="item">Item 3</div>
        <button id="updateButton">Update Items</button>
    
        <script>
            const updateButton = document.getElementById('updateButton');
    
            updateButton.addEventListener('click', () => {
                // Select all elements with the class 'item'
                const items = document.querySelectorAll('.item');
    
                // Loop through each selected element
                items.forEach((item, index) => {
                    // Update the innerHTML of each item
                    item.innerHTML = `Updated Item ${index + 1}`;
                });
            });
        </script>
    </body>
    </html>
    

    In this example:

    1. We have several <div> elements with the class item.
    2. We add an event listener to a button that, when clicked, selects all elements with that class using querySelectorAll().
    3. We iterate over the NodeList returned by querySelectorAll() using forEach().
    4. Inside the loop, we update the innerHTML of each selected element.

    When you click the "Update Items" button, the contents of each .item div will be updated accordingly.

Related Questions: