Loop through all Form elements using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

banner

Photo by Wira Dyatmika

Loop through all Form elements using JavaScript #

To loop through all elements in a form:

  1. Use the elements property on the form to get a collection of the form's elements.
  2. Use the Array.from() method to convert the collection to an array.
  3. Iterate over the elements using the forEach() 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" /> <input type="text" id="country" name="country" /> </form> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const form = document.getElementById('my-form') // 👇️ if you can't add an `id` to the form // const form = document.querySelector('form'); Array.from(form.elements).forEach(element => { console.log(element); });

We used the getElementById method to select the form element.

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

We used the Array.from method to convert the collection to an array, so we can call the forEach method on it.

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

You can also use a for...of loop to iterate over the elements in the form.

index.js
const form = document.getElementById('my-form'); for (const element of form.elements) { console.log(element); }

The for...of loop allows us to use the break keyword to break out of the loop if a certain condition is met.

index.js
const form = document.getElementById('my-form'); for (const element of form.elements) { console.log(element); if (element.value === 'hello') { break; } }

This would be a more efficient solution if you don't need to iterate over all of the form elements, but can break out once the work is done.

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