<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>HTMLFormElement: elements property / notebook
HTMLFormElement: elements property
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const inputs = document.getElementById("my-form").elements;
const inputByIndex = inputs[0];
const inputByName = inputs["username"];<form id="fullForm">
This form looks full, but it has no associated form controls
<fieldset form="sparseForm">
<legend>This is a legend</legend>
<label>A form control: <input form="sparseForm" /></label>
<label>Another form control: <input form="sparseForm" /></label>
<label>Yet another form control: <input form="sparseForm" /></label>
</fieldset>
</form>
<form id="sparseForm">
<object data="lone-form-control.jpg">Lone form control</object>
</form>const sparse = document.getElementById("sparseForm").elements;
const full = document.getElementById("fullForm").elements;console.log(`sparse form: ${sparse.length}`); // sparse form: 5
console.log(`full form: ${full.length}`); // full form: 0console.log(`first member: ${sparse[0].tagName}`); // first member: FIELDSET
console.log(`last member: ${sparse[sparse.length - 1].tagName}`); // last member: OBJECTconst inputs = document.getElementById("my-form").elements;
// Iterate over the form controls
for (const input of inputs) {
if (input.nodeName === "INPUT" && input.type === "text") {
// Update text input
input.value = input.value.toLocaleUpperCase();
}
}const inputs = document.getElementById("my-form").elements;
// Iterate over the form controls
for (const input of inputs) {
// Disable all form controls
input.setAttribute("disabled", "");
}