HTML DOM Document getElementsByName()
Example
Get all elements with the name "fname":
let elements = document.getElementsByName("fname");
Try it Yourself »
Number of elements with name="animal":
let num = document.getElementsByName("animal").length;
Try it Yourself »
More examples below.
Description
The getElementsByName()
method returns a collection of elements with a specified name.
The getElementsByName()
method returns a live NodeList.
NodeList
A NodeList is an array-like collection (list) of nodes.
The nodes in the list can be accessed by index. The index starts at 0.
The length Poperty returns the number of nodes in the list.
Syntax
document.getElementsByName(name)
Parameters
Parameter | Description |
name | Required. The value of the element's name attribute. |
Return Value
Type | Description |
Object | A NodeList Object. A collection of elements with the specified name. The elements are sorted as they appear in the document. |
More Examples
Check all <input> elements with type="checkbox" that have the name "animal":
const collection = document.getElementsByName("animal");
for (let i = 0; i < collection.length; i++) {
if (collection[i].type == "checkbox") {
collection[i].checked = true;
}
}
Try it Yourself »
Browser Support
document.getElementsByName()
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |