slayernoah slayernoah - 2 months ago 15
Javascript Question

JavaScript: Loop through all the elements returned from getElementsByTagName

I am trying to loop through all the elements retruned from

getElementsByTagName("input")
using forEach. Any ideas why this does not work in FF, Chrome or IE?

<html>
<head>
</head>
<body>
<input type="text" value="" />
<input type="text" value="" />
<script>
function ShowResults(value, index, ar) {
alert(index);
}
var input = document.getElementsByTagName("input");
alert(input.length);
input.forEach(ShowResults);
</script>
</body>
</html>


Thank you for your time!

Answer

You need to convert the nodelist to array with this:

<html>
    <head>
    </head>
    <body>
        <input type="text" value="" />
        <input type="text" value="" />
        <script>
            function ShowResults(value, index, ar) {
                alert(index);
            }
            var input = document.getElementsByTagName("input");
            var inputList = Array.prototype.slice.call(input);
            alert(inputList.length);
            inputList.forEach(ShowResults);
    </script>
    </body>
</html>

or use for loop.

for(i = 0;i < input.length; i++)
{
    ShowResults(input[i].value);
}

and change ShowResults function to:

function ShowResults(value) {
   alert(value);
}