Skip to content

JavaScript set input value by class name | Change value attribute example

  • by

Use getElementsByClassName return a list/array of elements. Pick an element through the index and set a value on the input element. You can also iterate over elements.

Use the getElementById method if only one element is needed to change value.

Example JavaScript set input value by class name

HTML example code :-

<html>
<body>

    <input class="in1" type="text" >
    <script>

        var els=document.getElementsByClassName("in1")[0];
        els.value = "Test Content"
    </script>

</body>

</html>

Output:

Example JavaScript set input value by class name

Another example

Loop over the array and set each element’s value. The getElementsByClassName() method returns a collection of an element’s child elements with the specified class name, as a NodeList object.

<html>
<body>

    <input class="in1" type="text" >
    <input class="in1" type="text" >
    <script>

        var els=document.getElementsByClassName("in1");
        for (var i=0;i<els.length;i++) {
            els[i].value = "New values";}
        </script>

    </body>

    </html>

Do comment if you have any suggestions or doubts on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *