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.
The getElementsByName()
method returns a collection of elements with a specified name.
The getElementsByName()
method returns a live 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.
document.getElementsByName(
name)
Parameter | Description |
name | Required. The value of the element's name attribute. |
Type | Description |
Object | A NodeList Object. A collection of elements with the specified name. The elements are sorted as they appear in the document. |
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 »
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!