Form elementsCollection

Form 对象参考手册Form Object

Example

Get the number of elements in the form:

var x = document.getElementById("myForm").elements.length;

Try it Yourself »

Definition and Usage

The elements collection returns all elements in a form as an array.

Note:The elements in the collection are sorted in the order they appear in the source code.

Note:The elements collection returns all elements in a <form>, not all <form> elements in the HTML document. To get all <form> elements, you can use thedocument.formscollection.

Syntax

formObject.elements

Browser Support

Collection
elements Yes Yes Yes Yes Yes

Properties

Property Description
length Returns the number of all elements in a <form>.

Note:This property is read-only.

Methods

Method Description
[index] Returns the element in a <form> with the specified index (starting at 0).

Note:If the index value exceeds the maximum index (or exceeds the specified range), null is returned.
item(index) Returns the element in a <form> with the specified index (starting at 0).

Note:If the index value exceeds the maximum index (or exceeds the specified range), null is returned.
namedItem(id) Returns the element in a <form> with the specified id.

Note:If the id does not exist, null is returned.

Example

Example

[index]

Get the value of the first element (index 0) in the form:

var x = document.getElementById("myForm").elements[0].value;

Try it Yourself »

Example

item(index)

Get the value of the first element (index 0) in the form:

var x = document.getElementById("myForm").elements.item(0).value;

Try it Yourself »

Example

Loop through and output the value of each element in the form:

var x = document.getElementById("myForm"); var txt = ""; var i; for (i = 0; i < x.length; i++) { txt = txt + x.elements[i].value + "<br>"; } document.getElementById("demo").innerHTML = txt;

Try it Yourself »


Form 对象参考手册Form Object Other Extensions