Javascript DOM HTML Form elements Collection

Introduction

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

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

Click button to display the number of elements in the form.

View in separate window

<!DOCTYPE html>
<html>
<body>

<form id="myForm" action="/action_page.php">
  First name: <input type="text" name="fname" value="CSS"><br>
  Last name: <input type="text" name="lname" value="HTML"><br>
  <input type="submit" value="Submit">
</form>/*from w  w w  . j  ava2 s .  com*/
<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.getElementById("myForm").elements.length;
  document.getElementById("demo").innerHTML = "Found " + x + " elements in the form.";
}
</script>

</body>
</html>

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

The elements collection returns all elements inside the <form> element.

To get all <form> elements in the document, use the document.forms collection instead.

Property
Description
length

Returns the number of elements in the <form> element.
This property is read-only
[index]

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

Returns the element in <form> with the specified index starting at 0.
Returns null if the index number is out of range
namedItem(id) Returns the element in <form> with the specified id.
Returns null if the id does not exist
Return Value:

An HTMLFormsControlCollection Object, representing all elements in a <form> element.
The elements in the collection are sorted in the sequence as they appear in the source code



PreviousNext

Related