如何遍历从 getElementsByTagName 返回的所有元素 [英] How to loop through all the elements returned from getElementsByTagName

查看:127
本文介绍了如何遍历从 getElementsByTagName 返回的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 forEach 遍历从 getElementsByTagName("input") 返回的所有元素.任何想法为什么这在 FF、Chrome 或 IE 中不起作用?

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>

推荐答案

您需要将节点列表转换为数组:

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>

或使用 for 循环.

or use for loop.

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

并将 ShowResults 函数更改为:

and change ShowResults function to:

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

为什么我们需要这样做?
JavaScript 中的一些对象看起来像一个数组,但它们不是一个.这通常意味着它们具有索引访问和长度属性,但没有任何数组方法.示例包括特殊变量参数、DOM 节点列表和字符串.类数组对象和通用方法提供了使用类数组对象的技巧.来源

2019 年 10 月 7 日更新
现在在 ES6 中你可以使用 [...inputList].forEachArray.from(inputList)

这篇关于如何遍历从 getElementsByTagName 返回的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆