HTMLFormElement: elements property
The HTMLFormElement
property elements
returns an HTMLFormControlsCollection
listing all the form controls contained in the <form>
element.
Independently, you can obtain just the number of form controls using the length
property.
You can access a particular form control in the returned collection by using either an index or the element's name
or id
attributes.
Prior to HTML 5, the returned object was an HTMLCollection
, on which HTMLFormControlsCollection
is based.
Note: Similarly, you can get a list of all of the forms contained within a given document using the document's forms
property.
Value
An HTMLFormControlsCollection
containing all non-image controls in the form. This is a live collection; if form controls are added to or removed from the form, this collection will update to reflect the change.
The form controls in the returned collection are in the same order in which they appear in the form by following a preorder, depth-first traversal of the tree. This is called tree order.
Only the following elements are returned:
Examples
Quick syntax example
In this example, we see how to obtain the list of form controls as well as how to access its members by index and by name or ID.
<form id="my-form">
<label>
Username:
<input type="text" name="username" />
</label>
<label>
Full name:
<input type="text" name="full-name" />
</label>
<label>
Password:
<input type="password" name="password" />
</label>
</form>
const inputs = document.getElementById("my-form").elements;
const inputByIndex = inputs[0];
const inputByName = inputs["username"];
This example gets the form's element list, then iterates over the list, looking for <input>
elements of type "text"
so that some form of processing can be performed on them.
const inputs = document.getElementById("my-form").elements;
for (let i = 0; i < inputs.length; i++) {
if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text") {
inputs[i].value.toLocaleUpperCase();
}
}
const inputs = document.getElementById("my-form").elements;
for (let i = 0; i < inputs.length; i++) {
inputs[i].setAttribute("disabled", "");
}
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
elements |
1 |
12 |
1 |
5.5 |
8 |
3 |
4.4 |
18 |
4 |
10.1 |
1 |
1.0 |