Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use getElementsByName method in Javascript with Example
7947 Views
GetElementsByName method 
document.getElementsByName method in javascript used to get all the nodes has the give name as the parameter.

document.getElementsByName(name of the node)
<input type="text" name="txt_username" />
<input type="text" name="txt_username" />
<input type="text" name="txt_username" />

node means element here node is input. name is txt_username.
document.getElementsByName("txt_username") returns three nodes.
can get no of nodes by
document.getElementsByName("txt_username").length

document.getElementsByName("txt_username")[0]
document.getElementsByName("txt_username")[1]
document.getElementsByName("txt_username")[2]
to access the nodes.
Example
<html>
    <head>
        <title>getElementsByName example</title>
        <script type="text/javascript">
            function show(){
                var userNames = document.getElementsByName("txt_username");
                if (userNames.length != 0){
                   var userNameString = "";
                   for (var i=0;i<userNames.length;i++){
                      userNameString += userNames[i].value + "<br />";
                   }
                   document.write(userNameString);
                }
                else {
                   alert("No name found as txt_username");
                }
            }
        </script>
    </head>
    <body>
        <form id="frm_userinfo">
           Name 1: <input type="text" name="txt_username" /><br />
           Name 2: <input type="text" name="txt_username" /><br />
           Name 3: <input type="text" name="txt_username" /><br />
        </form>

        <button onclick="javascript:return show();">Show</button>         
    </body>
</html>
Demo 
Best Lessons of "Good Javascript Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details