The getElementsByName() method is a specialized DOM selection tool that returns a live NodeList containing all elements in the document that possess a specific name attribute. While many selection methods target tags, IDs, or classes, this method is primarily used in the context of HTML Forms, where the name attribute is the standard way to group elements (like radio buttons) and identify data sent to a server.

1. Syntax and Core Mechanism

The method is accessed via the document object. Unlike getElementById, which returns a single element, getElementsByName always returns a collection, even if only one match is found.

JavaScript
const elements = document.getElementsByName(nameString);

Parameters

  • nameString (Required): A string representing the value of the name attribute you are searching for. This is case-sensitive in most modern browsers.

Return Value

  • Live NodeList: A collection of elements. A “live” collection means that if elements are added or removed from the DOM after the method is called, the NodeList updates itself automatically.

2. Primary Use Case: Handling Radio Buttons

The most critical use of getElementsByName() is managing radio button groups. In HTML, radio buttons belong to the same group if they share the same name. This method allows you to retrieve the entire group to determine which option the user has selected.

JavaScript
// HTML: 
// <input type="radio" name="gender" value="male"> Male
// <input type="radio" name="gender" value="female"> Female

const genderGroup = document.getElementsByName("gender");

function getSelectedGender() {
    for (let i = 0; i < genderGroup.length; i++) {
        if (genderGroup[i].checked) {
            return genderGroup[i].value;
        }
    }
    return "None selected";
}

3. Key Characteristics and Nuances

A. The “Live” Nature

Unlike querySelectorAll (which returns a static “snapshot”), the NodeList returned by getElementsByName reflects the current state of the DOM.

JavaScript
const inputs = document.getElementsByName("user-input");
console.log(inputs.length); // Assuming 2 elements exist

// If you dynamically inject another <input name="user-input">
// inputs.length will automatically become 3 without re-calling the method.

B. NodeList vs. Array

While a NodeList looks like an array and supports .length and .forEach(), it is not a JavaScript Array. You cannot use methods like .map(), .filter(), or .reduce() directly on it. To do so, you must convert it:

JavaScript
const arrayVersion = Array.from(document.getElementsByName("myField"));

C. Scope

This method is only available on the document object. You cannot call someDiv.getElementsByName("..."). If you need to find named elements within a specific sub-section of the page, you must use querySelector or querySelectorAll with an attribute selector:

JavaScript
const subset = container.querySelectorAll('[name="myField"]');

4. Modern Alternative: Attribute Selectors

In modern development, many programmers prefer using querySelectorAll because it is more versatile and can be called on individual elements rather than just the document.

JavaScript
// Functionally similar to getElementsByName, but static
const radios = document.querySelectorAll('input[name="payment-method"]');

5. Practical Implementation: Form Reset Logic

You can use getElementsByName() to target specific fields across different sections of a form to clear them without resetting the entire form object.

JavaScript
function clearNamedFields(targetName) {
    const fields = document.getElementsByName(targetName);
    fields.forEach(field => {
        if (field.type === 'text' || field.tagName === 'TEXTAREA') {
            field.value = '';
        } else if (field.type === 'checkbox' || field.type === 'radio') {
            field.checked = false;
        }
    });
}

// Clears all inputs where name="tracking-code"
clearNamedFields("tracking-code");

Categorized in:

JS DOM,