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

Find out which elements are returned by 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="foo@bar.com" />
    <label for="age" />
    <input type="number" id="age" name="age" min="18" max="60" value="18" />

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

console.log(formElems.email.value); // output: 'foo@bar.com'
console.log(formElems.age.value); // output: '18'

console.log(formElems[0].value); // output: 'foo@bar.com'
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.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.