Latest web development tutorials
 

HTML DOM getElementsByName() Method

< Document Object

Example

Get all elements with the specified name:

var x = document.getElementsByName("fname");
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The getElementsByName() method returns a collection of all elements in the document with the specified name (the value of the name attribute), as a NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Tip: You can use the length property of the NodeList object to determine the number of elements with the specified name, then you can loop through all elements and extract the info you want.

Note: In HTML5, the "name" attribute is deprecated and has been replaced by the "id" attribute for many elements. Use the document.getElementById() method where it is appropriate. Also look at the getElementsByClassName() and getElementsByTagName() methods.


Browser Support

Method
getElementsByName() Yes Yes Yes Yes Yes

Syntax

document.getElementsByName(name)

Parameter Values

Parameter Type Description
name String Required. The name attribute value of the element you want to access/manipulate

Technical Details

DOM Version: Core Level 1 Document Object
Return Value: A NodeList object, representing a collection of elements with the specified name. The elements in the returned collection are sorted as they appear in the source code.

Examples

More Examples

Example

Find out how many elements there are in the document that have a name attribute with the value "animal" (using the length property of the NodeList object):

var x = document.getElementsByName("animal").length;
Try it Yourself »

Example

Check all <input> elements with type="checkbox" in the document that have a name attribute with the value "animal":

var x = document.getElementsByName("animal");
var i;
for (i = 0; i < x.length; i++) {
    if (x[i].type == "checkbox") {
        x[i].checked = true;
    }
}
Try it Yourself »

< Document Object