Latest web development tutorials
 

Form elements Collection

< Form Object

Example

Find out how many elements there are in a specified <form> element:

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

The result of x will be:

3
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The elements collection returns a collection of all elements in a form.

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

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


Browser Support

Collection
elements Yes Yes Yes Yes Yes

Syntax

formObject.elements

Properties

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

Note: This property is read-only

Methods

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

Note: Returns null if the index number is out of range
item(index) Returns the element in <form> with the specified index (starts at 0).

Note: Returns null if the index number is out of range
namedItem(id) Returns the element in <form> with the specified id.

Note: Returns null if the id does not exist

Technical Details

DOM Version: Core Level 2 Document Object
Return Value: An HTMLFormsControlCollection Object, representing all elements in a <form> element. The elements in the collection are sorted as they appear in the source code

Examples

More Examples

Example

[index]

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

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

The result of x will be:

Donald
Try it Yourself »

Example

item(index)

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

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

The result of x will be:

Donald
Try it Yourself »

Example

namedItem(id)

Get the value of the element with name="fname" in a form:

var x = document.getElementById("myForm").elements.namedItem("fname").value;

The result of x will be:

Donald
Try it Yourself »

Example

Loop through all elements in a 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 txt will be:

Donald
Duck
Submit
Try it Yourself »

< Form Object