Easy Tutorial
❮ Event Onstalled Prop Style Outlinestyle ❯

Form elements Collection


Example

Get the number of elements in a form:

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

Definition and Usage

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

Note: The elements are ordered as they appear in the source code.

Note: The elements collection returns all elements within a <form> element, not all <form> elements in the HTML document. To get all <form> elements, use the document.forms collection.

Syntax

formObject.elements

Browser Support

Collection Chrome Edge Firefox Safari Opera
elements Yes Yes Yes Yes Yes

Properties

Property Description
length Returns the number of elements in the <form>. <br> <br> Note: This property is read-only.

Methods

Method Description
[index] Returns the element at the specified index (starting from 0) in the <form>. <br> <br> Note: Returns null if the index is out of range.
item(index) Returns the element at the specified index (starting from 0) in the <form>. <br> <br> Note: Returns null if the index is out of range.
namedItem(id) Returns the element with the specified id in the <form>. <br> <br> Note: Returns null if the id does not exist.

Example

[index]

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

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

Example

item(index)

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

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

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;

❮ Event Onstalled Prop Style Outlinestyle ❯