Javascript getElementsByName Example

Updated on 23 Mar 2012,
Published on 30 Apr 2009

Javascript getElementsByName returns an array collection of HTML elements of specified name. Javascript for loop can be used to get the value stored as HTML element at each index of the array returned by the getElementsByName method of Javascript. You can use the length property and item and tags functions of getElementsByName method of Javascript document object as we learnt in the previous tutorial about Javascript document getElementsByName method. Here we will use the Javascript for loop through the array elements returned by the getElementsByName method.

JavaScript DOM Examples:

You can see the live samples and examples of JavaScript DOM from the following links:

Example of Javascript getElementsByName Loop

    <title>Javascript getElementByName</title>

    <script type="text/javascript">
        function getValues(objName) {
            var arr = new Array();
            arr = document.getElementsByName(objName);

            alert("total objects with name \"textfield\" = \n"
                 + arr.length);

            for (var i = 0; i < arr.length; i++) {
                var obj = document.getElementsByName(objName).item(i);

                alert( + " =  " + obj.value);
    <input id="Text1" 
            value="Hello" />
            <br />
    <input id="Text2" 
            value="World" />
            <br />
    <input id="Text3" 
            value="!!!" />
            <br />

    <input id="Button1" 
            onclick="getValues('textfield')" />

Above example code for Javascript getElementsByName loop will return all HTML elements stored in array collection. For loop is used to read each element stored at array index. Copy and paste the above code to create an HTML web page and run it in a web browser, click on the button, it will display the alert message box displaying number of elements stored in array generated by getElementsByName method. Further it will pop up other message boxes displaying the values of input type text elements whose name attribute value has been specified as a parameter to the getElementsByName method in the above example code.


You can see the output of above discussed code from the following link:

JavaScript document.getElementsByName 

Continue to next tutorial: Javascript Code to Change Span innerText to learn how to change the contents of HTML span element.

3 Responses to "Javascript getElementsByName Example"
good post
Thanks a lot. I was looking for that :D
Thanks.. !!
Leave a Comment
* required
* required
* will not be published
* optional
* hint:
  • Subscribe via Email