JavaScript - document.getElementsByName() Method

The getElementsByName() method in JavaScript returns all elements with the specified name attribute. This method is commonly used to retrieve elements in forms, especially radio buttons and checkboxes, where multiple elements may have the same name.

Syntax


document.getElementsByName("name");

In the syntax above, the name is a required attribute to specify the element you want to access.

Example of document.getElementsByName() Method

In this example, we count the total number of gender inputs (radio buttons) on the form using the getElementsByName() method:

Example


<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function totalelements() {
            var allgenders = document.getElementsByName("gender");
            alert("Total Genders: " + allgenders.length);
        }
    </script>
</head>
<body>
    <form>
        Male: <input type="radio" name="gender" value="male">
        Female: <input type="radio" name="gender" value="female">
        <br><br>
        <input type="button" onclick="totalelements()" value="Total Genders">
    </form>
</body>
</html>
    

Output

When the "Total Genders" button is clicked, an alert will display the total number of gender options (2 in this example). Male: Female: