Borislav Hadzhiev
Last updated: Jan 11, 2022
Check out my new book
To get all the elements in a form:
elements
property to get a collection of the form's elements.Array.from()
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" /> <textarea id="message" name="message" rows="5" cols="30"></textarea> <input type="submit" value="Submit" /> </form> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const form = document.getElementById('my-form'); // ✅ Get all form elements const formElements = Array.from(form.elements); formElements.forEach(element => { console.log(element); }); console.log('-----------------'); // ✅ Get only input elements in form const onlyInputs = document.querySelectorAll('#my-form input'); onlyInputs.forEach(input => { console.log(input); });
We selected the
form element
using the document.getElementById()
method.
The elements property on the form returns a collection containing all of the form controls.
input
elements, textarea
, select
elements, etc.If you need to use any array-specific methods on the collection, you should convert it to an array using the Array.from method.
The function we passed to the forEach method gets called with each element in the array.
In the second example, we used the
querySelectorAll
method to only select the input
elements in the form.
const onlyInputs = document.querySelectorAll('#my-form input'); onlyInputs.forEach(input => { console.log(input); });
NodeList
that contains the matching elements.The selector you pass to the querySelectorAll
method can be as specific as
necessary. The following example selects only input
elements with type
of
text
inside of the form.
const onlyInputs = document.querySelectorAll( '#my-form input[type="text"]' ); onlyInputs.forEach(input => { console.log(input); });
The NodeList
from the example above does not include the input
element that
has a type of submit
.