JavaScript getElementsByName

Usage:

  • The getElementsByName() method is a built-in function of the document object. It allows you to select all elements in the DOM that share a specific name attribute. This is particularly powerful when working with forms, where multiple elements (like radio buttons) often share the same name to group their logic together.
Developer Tip: While modern developers often reach for querySelectorAll, getElementsByName is highly performant and specifically optimized for finding elements by their name attribute, making it a great tool for form processing.

Syntax:

var elements = document.getElementsByName(name);
  • name: This is a string representing the value of the name attribute you want to target. This is case-sensitive in most browsers, so ensure it matches your HTML exactly.

Return Value:

  • The method returns a live NodeList. A NodeList is an array-like collection of elements.
  • If the browser finds matching elements, they are included in the list in the order they appear in the document.
  • If no matching elements are found, the method returns an empty NodeList (length of 0).
Watch Out: A NodeList is "array-like," meaning you can access items via index (e.g., list[0]), but it does not have standard Array methods like .map(), .filter(), or .reduce() natively in older browsers.

Example:

In this example, we have two text inputs. We can target them specifically using the "username" name attribute.

<!-- HTML Structure -->
<input type="text" name="username" value="JohnDoe">
<input type="text" name="username" value="JaneDoe">
<input type="text" name="email" value="[email protected]">
// JavaScript Selection
var elements = document.getElementsByName('username');

console.log(elements.length); // Output: 2
console.log(elements[0].value); // Output: "JohnDoe"

Accessing Elements:

  • Because the result is a collection, you cannot modify all elements at once. You must iterate through them using a loop, such as a for loop or forEach.
  • Once you access an individual element via its index, you can manipulate its styles, values, or attributes.
Common Mistake: Forgetting that getElementsByName returns a collection even if there is only one matching element. You cannot call elements.value; you must call elements[0].value.

Live Collection:

  • The NodeList returned is live. This means that if you add or remove elements with that specific name attribute to the DOM after the variable has been defined, the variable will automatically update to reflect the current state of the document.
Best Practice: If you need to perform complex array operations (like filtering or mapping) on the returned elements, convert the NodeList to a true Array using Array.from(elements) or the spread operator [...elements].

Null Handling:

  • It is important to remember that getElementsByName() never returns null. If the search fails, you get an empty collection. Always check the .length property to see if your selection actually caught any elements.

Use Cases:

  • Radio Button Groups: Since all radio buttons in a single group share the same name, this method is the standard way to retrieve the entire group to check which one is "checked."
  • Form Validation: When processing multi-input forms where fields are dynamically generated with the same name (like a list of "guest_name" inputs).
  • Data Extraction: Quickly grabbing all inputs related to a specific data category before sending them to an API.

 

Key Points

  • getElementsByName() retrieves a collection of HTML elements based on their name attribute.
  • It returns a live NodeList, which stays in sync with changes in the DOM.
  • Individual elements are accessed using zero-based indexing (e.g., [0], [1]).
  • It is the most efficient way to handle groups of inputs, particularly radio buttons and checkboxes.
Best Practice: Use the name attribute for form data and the id attribute for unique styling or single-element selection. getElementsByName is your bridge for handling data-centric element groups.