How to Set an HTML Element Name Using JavaScript?

Estimated read time 1 min read

You can set the name attribute of an HTML element using JavaScript by accessing the element and modifying its name property. Here’s an example that sets the name attribute of an input element with an id of “myInput”:

<input id="myInput" type="text" name="oldName">

<button onclick="setInputName()">Set Input Name</button>

<script>
  function setInputName() {
    const input = document.getElementById("myInput");
    input.name = "newName";
  }
</script>

In the example above, the setInputName() function uses JavaScript to access the input element with an id of “myInput”. The function then sets the name attribute of the input element to “newName”. When the “Set Input Name” button is clicked, the function is triggered and changes the name attribute of the input element.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply