How to iterate through HTML Form Elements

Published on: June 11, 2017

Welcome to the 51st Easy JavaScript tutorial, part of EasyProgramming.net. Thanks for sticking around for the past 50 weeks! We're 2 weeks away from a full year of learning JS! Let's iterate through an HTML form, its fields, and its values.

We know how to read individual form element items, but let's go a little deeper and actually iterate through an entire form without having to get each element individually.

This is a great way to go through an entire form and do some validation, so feel free to play around with this knowledge. In this tutorial we introduce to you the .elements property that you can use to access everything inside of a form. 

Some example code looks something like this:

    var form = document.getElementById("myform").elements;
    form[0]; //to access the first element:

    form[0].type; //retrieve the input type e.g. text, number, etc.

    form[0].id; //retrieve the ID of the HTML element

To fork the fiddle and follow along: https://jsfiddle.net/easyjs/hxqqxxn3/
