JavaScript: Recorre todos los elementos devueltos desde getElementsByTagName


Estoy tratando de recorrer todos los elementos retruneados de getElementsByTagName("input") usando forEach. ¿Alguna idea de por qué esto no funciona en FF, Chrome o 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>
Author: slayernoah, 2013-10-11

8 answers

Necesita convertir la lista de nodos a matriz con esto:

<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>

O usar para bucle.

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

Y cambie la función ShowResults a:

function ShowResults(value) {
   alert(value);
}
 58
Author: Dvir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-11 18:24:55

Yay, ES6:

const children = [...parent.getElementsByTagName('tag')];
children.forEach((child) => { /* Do something; */ });

MDN Doc para Operador de Propagación(...)

 28
Author: jtheletter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-17 04:59:58

Porque input no es una matriz, es HTMLCollection Usar un bucle for sería mejor.

Y dado que HTMLCollection s son objetos similares a una matriz, puede call Array#forEach en él como este

Array.prototype.forEach.call(input, ShowResults);
 7
Author: grape_mao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-01 00:57:18

Es porque input es una colección html. la colección html no tiene forEach.

Puede convertirlo fácilmente a array por Array.prototipo.slice

Ejemplo:

function ShowResults(value, index, ar) {
            alert(index);
        }
        var input = document.getElementsByTagName("input");
        alert(input.length);
input = Array.prototype.slice.call(input)
        input.forEach(ShowResults);

Http://jsfiddle.net/fPuKt/1 /

 4
Author: Daniel Dykszak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-22 09:08:05

La razón por la que esto no funciona es porque 'getElementsByTagName' devuelve un objeto similar a una matriz en lugar de una matriz real. En caso de que no lo sepa, así es como se ven ambos :-

var realArray = ['a', 'b', 'c'];
var arrayLike = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3
};

Por lo tanto, ya que los objetos tipo matriz heredan del objeto '.prototype 'instead of' Array.prototype', esto significa que los objetos tipo Array no pueden acceder a métodos comunes de prototipos de Array como forEach(), push(), map(), filter () y slice().

Espero que ayuda!

 4
Author: Naman Sancheti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-08 11:36:54

HTMLCollections no tiene los mismos métodos que los arrays. Usted puede comprobar esto por punta esto en la consola javascript de su navegador.

var elements = document.getElementsByClassName('some-class');
'forEach' in elements;

Y la consola devolverá true si elements (en este caso) tiene un método llamado forEach para llamar.

 2
Author: Andrés Torres,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-11 18:28:28

En ES6 puede usar el operador spread para convertir una HTMLCollection en una matriz. vea esta pregunta Por qué no puedo usar Array.forEach en una colección de elementos Javascript?

input = [...input]
input.forEach(ShowResults)
 1
Author: inostia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:11

Hice esto:

HTMLCollection.prototype.map = Array.prototype.map;

Ahora puede usar el mapa en cada HTMLCollection.

document.getElementsByTagName("input").map(
    input => console.log(input)
);
 1
Author: Toni Almeida,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-07 00:46:54