return elements that match specified CSS selector(s)

Can querySelectorAll() be used to modify input values?

Answers:

  • The querySelectorAll() method in JavaScript is used to select multiple elements from the DOM that match a specified CSS selector. However, querySelectorAll() itself does not modify input values. Instead, it returns a NodeList of elements that you can then iterate over and manipulate.

    If you want to modify the values of input elements selected using querySelectorAll(), you can do so by accessing each element in the returned NodeList and setting its value property.

    Here’s an example:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Modify Input Values</title>
    </head>
    <body>
        <input type="text" class="my-input" value="Input 1">
        <input type="text" class="my-input" value="Input 2">
        <input type="text" class="my-input" value="Input 3">
        <button id="changeValues">Change Values</button>
    
        <script>
            document.getElementById('changeValues').addEventListener('click', () => {
                // Select all input elements with the class 'my-input'
                const inputs = document.querySelectorAll('.my-input');
    
                // Iterate over the NodeList and modify the value of each input
                inputs.forEach((input, index) => {
                    input.value = `Modified Input ${index + 1}`;
                });
            });
        </script>
    </body>
    </html>
    

    In this example:

    1. We use querySelectorAll('.my-input') to select all input elements with the class my-input.
    2. We use the forEach() method to iterate over the NodeList.
    3. Inside the loop, we set the value property of each input to a new string.

    As a result, when you click the "Change Values" button, all input fields will have their values modified.

Related Questions: