How to Set the Value of an HTML Element Using JavaScript by Class?

Estimated read time 2 min read

You can set the value of an HTML element using JavaScript by class by accessing the element(s) with the same class name and modifying its innerHTML or value property. Here’s an example that sets the value of all elements with a class of “myClass”:

<p class="myClass">Original Value</p>
<input class="myClass" type="text">

<button onclick="setValue()">Set Value</button>

<script>
  function setValue() {
    const elements = document.getElementsByClassName("myClass");
    for (const element of elements) {
      if (element.tagName === "INPUT") {
        element.value = "New Value";
      } else {
        element.innerHTML = "New Value";
      }
    }
  }
</script>

In the example above, the setValue() function uses JavaScript to access all elements with a class of “myClass” using the getElementsByClassName() method. The function then iterates over the elements and sets their value based on their tag name. If the element is an input element, its value property is set to “New Value”. Otherwise, its innerHTML property is set to “New Value”. When the “Set Value” button is clicked, the function is triggered and changes the value of all elements with a class of “myClass”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply