How to Get Elements by their name Attribute in JavaScript
Selecting form elements by their name attribute is a common requirement, especially when working with groups of radio buttons or submitting form data. The modern and most powerful way to select elements by any attribute, including name, is with CSS attribute selectors.
This guide will teach you how to use querySelector() and querySelectorAll() to find elements by their name attribute. You will learn how to perform an exact match, a partial match, and understand the difference between these modern methods and the classic getElementsByName().
The Modern Method (Recommended): querySelectorAll()
The document.querySelectorAll() method is the definitive tool for selecting DOM elements. It takes a CSS selector string as an argument and returns a static NodeList containing all elements that match the selector.
To select elements by their name attribute, you use the CSS attribute selector syntax: [name="value"].
HTML for Examples:
<input type="radio" name="color" value="red"> Red
<input type="radio" name="color" value="green"> Green
<input type="text" name="username">
Selecting by an Exact name Match
This is the most common use case. You want to find all elements where the name attribute is a specific, known value.
Problem: you need to get a collection of all radio buttons with the name "color".
Solution:
// Select all elements with a name attribute equal to "color"
const colorRadios = document.querySelectorAll('[name="color"]');
console.log(colorRadios.length); // Output: 2
colorRadios.forEach(radio => {
console.log(radio.value); // Prints 'red', then 'green'
});
This is the recommended best practice because it's consistent with how you select elements by class or ID.
To get only the first matching element, use document.querySelector():
const usernameInput = document.querySelector('[name="username"]');
Selecting by a Partial Match of the name Attribute
CSS attribute selectors also support powerful partial matching, which can be useful for finding groups of related elements.
Find all elements where the name starts with "user-"
Use the ^= operator.
<input name="user-firstname">
<input name="user-lastname">
const userFields = document.querySelectorAll('[name^="user-"]');
console.log(userFields.length); // Output: 2
Find all elements where the name ends with "-option"
Use the $= operator.
<input name="color-option">
<input name="size-option">
const optionFields = document.querySelectorAll('[name$="-option"]');
console.log(optionFields.length); // Output: 2
Find all elements where the name contains "email"
Use the *= operator.
<input name="primary-email">
<input name="secondary-email-address">
const emailFields = document.querySelectorAll('[name*="email"]');
console.log(emailFields.length); // Output: 2
The Classic Method: getElementsByName()
Before querySelectorAll() was widely available, the standard method for this task was document.getElementsByName(). This method is still functional but is considered less flexible.
Solution:
// This also selects all radio buttons with name="color"
const colorRadios = document.getElementsByName('color');
console.log(colorRadios.length); // Output: 2
Key Differences from querySelectorAll():
- Return Value:
getElementsByName()returns a liveNodeList, which automatically updates if elements are added or removed from the DOM.querySelectorAllreturns a staticNodeList, which is a snapshot in time. Static lists are often easier and safer to work with. - Flexibility:
getElementsByName()can only perform an exact match on thenameattribute. It does not support partial matching or combining with other selectors (likeinput[name="color"]).
Because of these limitations, querySelectorAll() is the superior and recommended choice in modern code.
Conclusion
For selecting elements by their name attribute in JavaScript, the choice is clear.
- The
document.querySelectorAll('[name="value"]')method is the recommended best practice. It is powerful, flexible, and consistent with all other modern DOM selection methods. - Use attribute selector variations (
^=,$=,*=) for powerful partial matching. - The older
document.getElementsByName()method is a functional but less flexible alternative that should generally be avoided in new code.