HOWTO · JavaScript

How to Get Element by Name in JavaScript

Learn how to get element by name in JavaScript.

On this page

To select every element whose HTML name attribute matches a value, use document.getElementsByName() or document.querySelectorAll() with a CSS attribute selector. The first method is made for matching name attributes; the second is useful when the selection also needs other CSS conditions. Both return a NodeList, so check its length before using the first item and iterate it when you need every match.

Get elements by name with getElementsByName()

document.getElementsByName(name) finds elements in the document whose name attribute equals the supplied string. It returns a NodeList, including when there are no matches; in that case its length is 0, not null. The returned collection is live, so its contents can reflect later changes to matching elements in the document.

For example, this HTML has two controls with the same name:

<label><input type="checkbox" name="interest" value="music" checked> Music</label>
<label><input type="checkbox" name="interest" value="reading"> Reading</label>

Here is a self-contained JavaScript example of the result handling. Its small document stand-in keeps the example runnable outside a browser; on a page, use the built-in document object with the same method call.

const controls = [
  { name: "interest", value: "music", checked: true },
  { name: "interest", value: "reading", checked: false },
];
const document = {
  getElementsByName(name) {
    return controls.filter((control) => control.name === name);
  },
};

const interests = document.getElementsByName("interest");
const firstInterest = interests.length > 0 ? interests[0].value : "No matches";
console.log(firstInterest);

for (const interest of interests) {
  if (interest.checked) {
    console.log(interest.value);
  }
}
music
music

The first value is read from the first matching control, whether or not it is checked; the loop prints only checked values. In a browser, document.getElementsByName("interest") returns the matching elements, and the same length check and iteration pattern applies. The method is convenient when the name attribute alone defines the selection.

Select elements by name with querySelectorAll()

document.querySelectorAll(selectors) accepts a CSS selector and returns a static NodeList of every matching element. To select elements by name, use an attribute selector such as input[name="interest"]; the tag condition limits the result to inputs, while the attribute condition matches the name. A selector can combine further CSS conditions or comma-separated alternatives when needed.

In a browser, select all matching inputs with document.querySelectorAll('input[name="interest"]'), then read the resulting NodeList with a length check or a loop. Use [name="interest"] alone to match that name on any element; prefix it with input when controls of other types should be excluded. In a selector, quotes delimit an attribute value; they do not escape quotes or backslashes inside it. Do not interpolate arbitrary dynamic values into this selector as-is. If you build a selector from a value, escape it for the CSS string context with a correct CSS string-escaping routine. When the value comes from input and you do not already have such a routine, avoid constructing a selector: call document.getElementsByName(value) and filter the returned elements by tag or other properties in JavaScript.

The runtime example below models the two inputs shown above because it has no browser DOM. In a page, use the same selector call with the built-in document object. Run this example:

const inputs = [
  { tagName: "INPUT", name: "interest", value: "music" },
  { tagName: "INPUT", name: "interest", value: "reading" },
];
const document = {
  querySelectorAll(selector) {
    if (selector !== 'input[name="interest"]') return [];
    return inputs.filter(
      (input) => input.tagName === "INPUT" && input.name === "interest",
    );
  },
};

const interests = document.querySelectorAll('input[name="interest"]');
if (interests.length === 0) {
  console.log("No matching inputs.");
} else {
  console.log(`Matches: ${interests.length}`);
  for (const input of interests) {
    console.log(input.value);
  }
}
Matches: 2
music
reading

This selects both inputs by tag and name, reports the count, and prints their values. The length check also keeps first-item access safe when no input matches.

This method returns a static NodeList. If the selector matches nothing, the collection is empty. The selector must be valid CSS; a malformed selector causes a SyntaxError. See the querySelectorAll() documentation for selector details.

Handle and compare the results

Both methods return collections rather than a single element or null. Check length before reading the first item, and use iteration when several matches matter. querySelectorAll() returns a static snapshot: later document changes do not update that collection. getElementsByName() returns a live collection, which can change as the document changes.

Choose getElementsByName() when the name attribute is the complete criterion. Choose querySelectorAll() when a CSS selector expresses the selection more clearly, such as limiting the name match to inputs or adding another attribute condition. If only one matching element is needed, querySelector() returns the first match or null; it does not return a collection. For additional selector syntax and behavior, consult the querySelectorAll() documentation.