What Is the Return Value of form.elements in JavaScript?

The HTMLFormElement.elements property returns an HTMLFormControlsCollection consisting of all (non-image) form controls contained in an HTML <form> element. It is a live collection that consists only of the following elements (if present in the form):

  • <button>
  • <fieldset>
  • <input> (except <input type="image" />)
  • <object>
  • <output>
  • <select>
  • <textarea>

The form controls in the returned HTMLFormControlsCollection are in the same order in which they appear in the form.

For example:

<form id="my-form">
    <label for="email" />
    <input type="email" id="email" name="email" value="[email protected]" />
    <label for="age" />
    <input type="number" id="age" name="age" min="18" max="60" value="18" />

    <input type="submit" />
</form>
const formElems = document.getElementById('my-form').elements;

console.log(formElems.email.value); // output: '[email protected]'
console.log(formElems.age.value); // output: '18'

console.log(formElems[0].value); // output: '[email protected]'
console.log(formElems[1].value); // output: '18'

console.log(formElems.length); // output: 3

As you can see from the example above:

  1. The <label> elements are not taken into account by the collection returned by HTMLFormElement.elements;
  2. The length property of the collection returns 3 because it also takes into account the <input type="submit" /> element.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.