HTMLFormElement: elements 属性
HTMLFormElement 接口的 elements 属性会返回一个 HTMLFormControlsCollection,其中列出了与 <form> 元素相关的所有表单控件。
您可以通过索引或元素的 name 或 id 属性来访问返回集合中的特定表单控件。
在 HTML5 之前,返回的对象是一个 HTMLCollection,而 HTMLFormControlsCollection 是基于它的。
独立地,您可以使用 length 属性获取相关表单控件的数量。您可以使用文档的 forms 属性来获取给定文档中所有表单的列表。
值
一个包含所有与表单相关的非图像控件的 HTMLFormControlsCollection。这是一个实时集合;如果表单控件与表单相关联或与之解除关联,该集合将更新以反映更改。
返回集合中的表单控件的顺序与它们在文档中出现的顺序相同,遵循树的先序深度优先遍历。这被称为树序。
仅返回以下表单控件:
<button><fieldset><input>(例外情况是,出于历史原因,其type为"image"的任何<input>都会被省略)<object><output><select><textarea>- 与表单关联的自定义元素
示例
快速语法示例
在此示例中,我们将展示如何获取表单控件列表,以及如何通过索引和名称或 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"];
关联的表单控件
此示例演示了 HTMLFormControlsCollection 如何包含与表单关联的表单控件,而不是物理嵌套在 <form> 中的控件。
第一个表单是完整的,有四个表单控件:一个 <fieldset> 和三个 <input> 元素。<legend> 和 <label> 元素不是列表中的表单控件。第二个表单是稀疏的,只有一个嵌套的表单控件:一个单独的 <object> 元素。完整表单中的所有表单控件都通过其 form 属性与稀疏表单相关联。
<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>Lone form control</object>
</form>
我们使用 elements 属性来获取每个表单的 HTMLFormControlsCollection。
const sparse = document.getElementById("sparseForm").elements;
const full = document.getElementById("fullForm").elements;
该集合包括表单元素的关联表单控件,即与表单关联的所有 <button>、<fieldset>、<input>、<object>、<output>、<select>、<textarea> 和与表单关联的自定义元素,即使这些元素嵌套在另一个表单中,或者未嵌套在任何表单中。
console.log(`sparse form: ${sparse.length}`); // sparse form: 5
console.log(`full form: ${full.length}`); // full form: 0
集合中的表单控件与它们在文档中出现的顺序相同。
console.log(`first member: ${sparse[0].tagName}`); // first member: FIELDSET
console.log(`last member: ${sparse[sparse.length - 1].tagName}`); // last member: OBJECT
访问表单控件
此示例获取表单的元素列表,然后遍历列表,查找类型为 "text" 的 <input> 元素,以便对它们执行某种形式的处理。
const 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", "");
}
规范
| 规范 |
|---|
| HTML # dom-form-elements-dev |
浏览器兼容性
加载中…