Accessing form elements
Learn to access form and input elements via form.elements and querySelector.
Accessing form elements
To reach a <form> element from JavaScript, you use document.querySelector. The form element's elements property gives all input fields inside the form as a collection.
const form = document.querySelector('form');
const inputs = form.elements;The elements collection lets you reach fields by name or index. This property exists only on form elements; it is not on other elements. The collection is a good starting point for working with forms.
Selecting a single field with querySelector
To reach a specific input field, you can use querySelector to select it. Selecting by the name attribute is the most common approach.
const email = document.querySelector('input[name="email"]');This method returns a single element. To walk all fields of a form, you use the elements collection; to pick one field, you use querySelector. Both serve the same goal; pick whichever feels easier.
Exercise Read the email field and log it
The form variable points to a <form> element. From the form.elements collection, assign the field named 'email' to an email variable and log its value with console.log.
Show example solution
const email = form.elements['email'];
console.log(email.value);
Test yourself
-
Which gives the collection of form fields?
const form = document.querySelector('form'); // A const a = form.children; // B const b = form.elements; // C const c = form.inputs; // D const d = form.fields;- A
- B
- C
- D
Show answer
B — Correct! The form.elements property exists only on forms and gives all fields.
-
Get the email field from elements
const form = document.querySelector('form'); const email = form.____['email'];Show answer
const form = document.querySelector('form'); const email = form.elements['email']; -
Match methods to their meanings
- document.querySelector('form')
- Selects the form element
- form.elements
- Gives all fields
- form.elements['email']
- Returns a field by name