HTML DOM Document getElementsByName() Method

Definition and Usage

getElementsByName() The method returns a collection of elements with the specified name.

getElementsByName() The method returns a real-time NodeList.

NodeList

NodeList Is a node collection similar to an array (list).

Nodes in the list can be accessed by index. The index starts from 0.

length The number of nodes in the returned list of properties.

Please refer to:

getElementById() method

getElementsByTagName() method

getElementsByClassName() method

querySelector() method

querySelectorAll() method

NodeList Reference Manual

Example

Example 1

Get all elements with name="fname":

let elements = document.getElementsByName("fname");

Try it yourself

Example 2

Return the number of elements with name="animal":

let num = document.getElementsByName("animal").length;

Try it yourself

Example 3

Check all <input> elements with type="checkbox" and 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

Syntax

document.getElementsByName(name)

Parameter

Parameter Description
name Required. The value of the element's name attribute.

Return value

Type Description
Object

NodeList object.

A collection of elements with the specified name.

Sorted according to the order of elements appearing in the document.

Browser support

document.getElementsByName() It is a DOM Level 1 (1998) feature.

All browsers support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support