How To Get All Elements In A Form Using JavaScript

Get all Elements in a Form using JavaScript

This guide will help you learn how to get all elements in a form using Javascript by two popular methods in HTML DOM. Follow the examples below to apply to your case.

Get all elements in a form using Javascript

Use the document.getElementsById() method

Here we have the Html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <form id="form1">
        <span>UserName</span>
        <input type="text" name="user" id="user"><br><br>
 
        <span>Password</span>
        <input type="password" name="password" id="password"><br><br>
 
        <label>
            <input type="checkbox" name="remember">
            <span>Remember Me</span>
        </label>
 
        <input type="submit" value="Submit">
    </form>
    <script src="getEleInForm.js"></script>
</body>
</html>

First, define a variable that will fetch our form using the document.getElementById() method.

Next, to get each element, we will use the forEach iterator function to iterate over each element in the array converted from the list of the form elements using the spread operator (…).

We use the elements property on the form to list all the form controls.

Code sample

let myForm = document.getElementById('form1');
 
// Convert form to array and loop through each element
[...myForm.elements].forEach((element)=>{
    console.log(element);
})

Output

<input type="text" name="user" id="user">
<input type="password" name="password" id="password">
<input type="checkbox" name="remember">
<input type="submit" value="Submit">

Use the document.querySelector() method

We don’t use the getElementById() method for the second solution but replace it with the document.querySelector() method.

The querySelector() method will return all elements in the result set found by the CSS selector provided when calling the method as a NodeList object. 

The NodeList object will represent a list of nodes. The index will access the nodes, and the index of the list will start from 0.

Code sample

let myForm = document.querySelector('#form1');
 
// Get the length of the form
let lengthForm = myForm.elements.length;
 
// Display each form element
for(let i = 0; i < lengthForm; i++){
    console.log(myForm.elements[i]);
}

Output

<input type="text" name="user" id="user">
<input type="password" name="password" id="password">
<input type="checkbox" name="remember">
<input type="submit" value="Submit">

Summary

Above, I showed you how to get all elements in a form using Javascript with two solutions. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *