Borislav Hadzhiev
Mon Jan 10 2022·2 min read
Photo by Wira Dyatmika
To loop through all elements in a form:
elements
property on the form to get a collection of the form's
elements.Array.from()
method to convert the collection to an array.forEach()
method.Here is the HTML for the examples in this article.
<!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.
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.
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.
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.
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.