javascript
  1. javascript-getelementsbyname

JavaScript getElementsByName

Heading h1

The getElementsByName method in JavaScript is used to query and retrieve all HTML elements that match a specified name attribute.

Syntax

The syntax for using the getElementsByName method is as follows:

var elementsArray = document.getElementsByName(name);

Parameters

The name parameter is the string that represents the name attribute of the HTML element(s) to be retrieved.

Return Value

The getElementsByName method returns an array of HTML elements that have a matching name attribute. If no matching elements are found, an empty array is returned.

Example

Consider the following HTML code:

<form>
  <input type="text" name="firstname">
  <input type="text" name="lastname">
  <input type="submit" value="Submit">
</form>

To retrieve the input fields using the getElementsByName method, we can use the following JavaScript:

var firstname = document.getElementsByName("firstname")[0];
var lastname = document.getElementsByName("lastname")[0];

Output

After executing the above JavaScript code, the firstname and lastname variables will contain the corresponding input field elements.

Explanation

The getElementsByName method searches the entire DOM (Document Object Model) for elements with a matching name attribute. The returned array contains all the elements that match the specified name, regardless of their location in the DOM.

If multiple elements have the same name, the getElementsByName method returns an array of all matching elements.

Use

The getElementsByName method is commonly used when working with HTML forms. It allows developers to easily retrieve input field values submitted by users, without having to manually traverse the DOM.

Important Points

  • The getElementsByName method returns an array of all HTML elements with a matching name attribute.
  • The returned array contains all elements that match the specified name, regardless of their location in the DOM.
  • If multiple elements have the same name, the getElementsByName method returns an array of all matching elements.
  • The getElementsByName method is commonly used with HTML forms to retrieve input field values.

Summary

The getElementsByName method in JavaScript is a powerful tool for querying and retrieving HTML elements with a specified name attribute. By using this method, developers can easily retrieve input field values submitted by users, without having to manually traverse the DOM.

Published on: