How to loop through all the elements returned from getElementsByTagName

slayernoah picture slayernoah · Oct 11, 2013 · Viewed 92.4k times · Source

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>

Answer

Dvir picture Dvir · Oct 11, 2013

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(let i = 0;i < input.length; i++)
{
    ShowResults(input[i].value);
}

and change ShowResults function to:

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

Why do we need to do that?
Some objects in JavaScript look like an array, but they aren’t one. That usually means that they have indexed access and a length property, but none of the array methods. Examples include the special variable arguments, DOM node lists, and strings. Array-Like Objects and Generic Methods gives tips for working with array-like objects. source

UPDATE for 07.10.2019
Nowdays with ES6 you can use [...inputList].forEach, or Array.from(inputList)