Javascript get all element in form

Get all form’s elements in JavaScript

When working with forms, there are cases when you need to get all of the form elements in a nice and structured way. JavaScript offers a native way to get all of the form’s elements.

Get all element

Consider the following HTML form:

 class="newsletter-form">  for="name">Name:  type="text" name="name" id="name" required>   for="email">Email:  type="email" name="email" id="email" required>   for="newsletter">I'd like to receive newsletter:  type="checkbox" name="newsletter" id="newsletter">   type="submit" name="submit">Subscribe   

To get all form elements use the elements property on a form tag.

const form = document.querySelector('.newsletter-form') form.elements // HTMLFormControlsCollection(8) [fieldset, input#name, fieldset, input#email, fieldset, input#newsletter, fieldset, button, name: input#name, email: input#email, newsletter: input#newsletter, submit: button] 

In the console it will look as follows:

All form

As you can see elements property will return an HTMLCollection.

To access items you can use it as an Array to access by index or as an Object to access via name property which corresponds to the HTML name attribute.

The elements that are returned via the elements property will contain the following elements:

To convert HTMLCollection to an Array you can use Array.from() method.

Now you can use forEach to iterate over this Array and find specific items.

Other benefit of having an Array instead of HTMLCollection is that you can use Array methods like .map() , .filter() , .sort() , etc.

const form = document.querySelector('.newsletter-form') Array.from(form.elements) // (8) [fieldset, input#name, fieldset, input#email, fieldset, input#newsletter, fieldset, button] 

All form

Get only inputs

If you want to get only input elements then you can use the querySelectorAll() method.

const formElements = document.querySelectorAll('.newsletter-form input') formElements // NodeList(3) [input#name, input#email, input#newsletter] 

Form

In this case, you’ll get a NodeList of input elements. Similar to HTMLCollection, it is not an Array, so you won’t be able to use Array methods until you convert it to an Array.

const formElements = document.querySelectorAll('.newsletter-form input') Array.from(formElements) // (3) [input#name, input#email, input#newsletter] 

Conclusion

Use elements property when you need to get each form element. The HTMLCollection offers a way to access items via their name. However, if you want to iterate over it, you’ll need to convert it to an Array.

On the other hand, you can always use the for loop to iterate over HTMLCollection, and then use the name property.

To get a set of specific form elements you can use the querySelectorAll() method and specify the elements you wish to get. This approach would make sense to get specific form elements, for example, certain inputs that are confined within a fieldset element.

Источник

Javascript get all element in form

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Table of Contents

# Get all of a Form’s elements using JavaScript

To get all the elements in a form:

  1. Select the form element.
  2. Use the elements property to get a collection of the form’s elements.
  3. Optionally, convert the collection to an array using the Array.from() method.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> 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.

Copied!
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 the input elements in a form const onlyInputs = document.querySelectorAll('#my-form input'); onlyInputs.forEach(input => console.log(input); >);

We selected the form element using the document.getElementById() method.

Copied!
const form = document.getElementById('my-form');

The elements property on the form returns a collection containing all of the form controls.

Copied!
const form = document.getElementById('my-form'); // ✅ Get all form elements const formElements = Array.from(form.elements);

Источник

Form elements Collection

Find out how many elements there are in a specified element:

More «Try it Yourself» examples below.

Description

The elements collection returns a collection of all elements in a form.

Note: The elements in the collection are sorted as they appear in the source code.

Note: The elements collection returns all elements inside the element, not all elements in the document. To get all elements in the document, use the document.forms collection instead.

Browser Support

Syntax

Properties

Property Description
length Returns the number of elements in the element.

Methods

Method Description
[index] Returns the element in with the specified index (starts at 0).

Technical Details

DOM Version: Core Level 2 Document Object
Return Value: An HTMLFormsControlCollection Object, representing all elements in a element. The elements in the collection are sorted as they appear in the source code

More Examples

Example

Get the value of the first element (index 0) in a form:

Example

Get the value of the first element (index 0) in a form:

Example

Get the value of the element with name=»fname» in a form:

Example

Loop through all elements in a form and output the value of each element:

var x = document.getElementById(«myForm»);
var txt = «»;
var i;
for (i = 0; i < x.length; i++) txt = txt + x.elements[i].value + "
«;
>
document.getElementById(«demo»).innerHTML = txt;

The result of txt will be:

Источник

HTMLFormElement: elements property

The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the element.

Independently, you can obtain just the number of form controls using the length property.

You can access a particular form control in the returned collection by using either an index or the element’s name or id attributes.

Prior to HTML 5, the returned object was an HTMLCollection , on which HTMLFormControlsCollection is based.

Note: Similarly, you can get a list of all of the forms contained within a given document using the document’s forms property.

Value

An HTMLFormControlsCollection containing all non-image controls in the form. This is a live collection; if form controls are added to or removed from the form, this collection will update to reflect the change.

The form controls in the returned collection are in the same order in which they appear in the form by following a preorder, depth-first traversal of the tree. This is called tree order.

Only the following elements are returned:

Examples

Quick syntax example

In this example, we see how to obtain the list of form controls as well as how to access its members by index and by name or ID.

form id="my-form"> label> Username: input type="text" name="username" /> label> label> Full name: input type="text" name="full-name" /> label> label> Password: input type="password" name="password" /> label> form> 
const inputs = document.getElementById("my-form").elements; const inputByIndex = inputs[0]; const inputByName = inputs["username"]; 

Accessing form controls

This example gets the form’s element list, then iterates over the list, looking for elements of type «text» so that some form of processing can be performed on them.

const inputs = document.getElementById("my-form").elements; // Iterate over the form controls for (let i = 0; i  inputs.length; i++)  if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text")  // Update text input inputs[i].value.toLocaleUpperCase(); > > 

Disabling form controls

const inputs = document.getElementById("my-form").elements; // Iterate over the form controls for (let i = 0; i  inputs.length; i++)  // Disable all form controls inputs[i].setAttribute("disabled", ""); > 

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

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:

    UserName Password  Remember Me   

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); >)

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

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:

Hi, my name is Joni Smith. My job is a programmer. I love learning programming languages, especially C++, C#, php, javascript, html, css. I want to share them with you. I hope my articles will bring a lot of useful knowledge to you.

Name of the university: HVNH BA
Major: htttql MIS
Programming Languages: C++, C#, php, javascript, html, css

Источник

Читайте также:  String to image in javascript
Оцените статью