Follow The New Tutorial updates on WhatsApp, Telegram or YouTube.

Javascript – document.getElementsByName() method

The document.getElementsByName() method returns all the element of the specified name. It is useful when you want to get all elements with the specified name.

Syntax

document.getElementsByName("name")

name“: It is the name attribute value of the element you want to access or manipulate. It is required.

Return Value

HTMLCollection: It is a collection of all elements in the document with the specified class name.

  • The HTMLCollection object represents a collection of nodes.
  • The nodes can be accessed by index numbers.
  • The index starts at 0.
  • length property of the HTMLCollection object is used to determine the number of elements with a specified class name. This is useful when you want to loop through all elements and extract the info you want.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript getElementsByName() method Example</title>
</head>

<body>
    <!-- In this example, we going to count total number of genders. Here, we are using getElementsByName() method to get all the genders. -->
    <script type="text/javascript">
        function totalelements() {
            var allgenders = document.getElementsByName("gender");
            alert("Total Genders:" + allgenders.length);
        }  
    </script>
    <form>
        Male:<input type="radio" name="gender" value="male">
        Female:<input type="radio" name="gender" value="female">

        <input type="button" onclick="totalelements()" value="Total Genders">
    </form>
</body>

</html>
JavaScript getElementsByName() method Example – Ouput