Categories
JavaScript Answers

How to access form elements by HTML ID or name attribute with JavaScript?

Spread the love

To access form elements by HTML ID or name attribute with JavaScript, we use the elements property.

For instance, we write

<form id="myForm">
  <input type="text" name="foo" />
</form>

to add a form.

Then we write

const fooInput = document.getElementById("myForm").elements["foo"];

to get the input inside the form.

We select the form with getElementById.

And then we get the input with the elements["foo"] property.

'foo' is the name attribute value of the input.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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