How to loop through elements of a form with JavaScript

Marika Lam
1 min readSep 29, 2022

In order to loop through elements of a form, you will first need to retrieve the form elements. Once you get a reference of your form, then you can iterate the elements collection.

Method #1: using getElementById

var elements = document.getElementById("my-form").elements;

for (var i = 0, element; element = elements[i++];) {
if (element.type === "text" && element.value === "")
console.log("it's an empty textfield")
}

Method #2: using querySelectorAll

var elements = document.querySelectorAll("#my-form input[type=text]")

for (var i = 0, element; element = elements[i++];) {
if (element.value === "")
console.log("it's an empty textfield")
}

Amazon Links to “Must-Haves” as a WFH Software Engineer 🙂💻

24-inch budget-friendly monitor, Portable monitor, Laptop stand, Waterproof desk mat, Keyboard cleaning gel, Six-outlet wall charger and surge protector,, Wi-Fi extender, Blue-light–blocking glasses, Memory foam gel pad, Foam footrest

Courses to learn more about datastructures/algorithms ✍️

Stanford, Duke, UCSD

Courses to learn more about databases 👓

DB Foundations, Data Scientists specialization

Courses to learn more about React 🧢

Full-Stack WebDev, Front-End WebDev with React, IBM Full Stack

--

--

No responses yet