Get all Elements in a Form using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 11, 2022

banner

Check out my new book

Get all Elements in a Form using JavaScript #

To get all the elements in a form:

  1. Select the form element.
  2. Use the elements property to get a collection of the form's elements.
  3. Optionally, convert the collection to an array using the Array.from() method.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <form id="my-form"> <input type="text" id="first_name" name="first_name" /> <input type="text" id="last_name" name="last_name" /> <textarea id="message" name="message" rows="5" cols="30"></textarea> <input type="submit" value="Submit" /> </form> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const form = document.getElementById('my-form'); // ✅ Get all form elements const formElements = Array.from(form.elements); formElements.forEach(element => { console.log(element); }); console.log('-----------------'); // ✅ Get only input elements in form const onlyInputs = document.querySelectorAll('#my-form input'); onlyInputs.forEach(input => { console.log(input); });

We selected the form element using the document.getElementById() method.

The elements property on the form returns a collection containing all of the form controls.

The collection includes input elements, textarea, select elements, etc.

If you need to use any array-specific methods on the collection, you should convert it to an array using the Array.from method.

The function we passed to the forEach method gets called with each element in the array.

In the second example, we used the querySelectorAll method to only select the input elements in the form.

index.js
const onlyInputs = document.querySelectorAll('#my-form input'); onlyInputs.forEach(input => { console.log(input); });
The method takes a string containing a valid CSS selector as a parameter and returns a NodeList that contains the matching elements.

The selector you pass to the querySelectorAll method can be as specific as necessary. The following example selects only input elements with type of text inside of the form.

index.js
const onlyInputs = document.querySelectorAll( '#my-form input[type="text"]' ); onlyInputs.forEach(input => { console.log(input); });

The NodeList from the example above does not include the input element that has a type of submit.

Use the search field on my Home Page to filter through my more than 3,000 articles.