Form elements collection
Definition and Usage
elements
The set returns a collection of all elements in the form.
Note:The elements in the set are sorted in the order they appear in the source code.
Note:The elements collection returns all elements within the <form> element, not all <form> elements in the document. If you need to get all <form> elements in the document, please use document.forms collection.
Instance
Example 1
Find out how many elements there are in the specified <form> element:
var x = document.getElementById("myForm").elements.length;
The result of x will be:
3
Tip:More examples are provided below the page.
Syntax
formObject.elements
Property
Property | Description |
---|---|
length |
Returns the number of elements in the <form> element. Note:This property is read-only. |
Method
Method | Description |
---|---|
[index] |
Returns the element with the specified index in the <form> (starting from 0). Note:Returns null if the index number is out of range. |
item(index) |
Returns the element with the specified index in the <form> (starting from 0). Note:Returns null if the index number is out of range. |
namedItem(id) |
Returns the element with the specified id in the <form>. Note:Returns null if the id does not exist. |
Technical details
DOM version: | Core Level 2 Document Object |
---|---|
Return value: |
HTMLFormsControlCollection object, representing all elements in the <form> element. The elements in the collection are sorted in the order they appear in the source code. |
More examples
Example 2: [index]
Get the value of the first element in the form (index 0):
var x = document.getElementById("myForm").elements[0].value;
The result of x will be:
Donald
Example 3: item(index)
Get the value of the first element in the form (index 0):
var x = document.getElementById("myForm").elements.item(0).value;
The result of x will be:
Donald
Example 4: namedItem(id)
Get the value of the element with name="fname" in the form:
var x = document.getElementById("myForm").elements.namedItem("fname").value;
The result of x will be:
Donald
Example 5
Loop through all elements in the form and output the value of each element:
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;
The result of x will be:
Donald Duck Submit
Browser Support
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support |