如何遍历从getElementsByTagName返回的所有元素 [英] How to loop through all the elements returned from 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(i = 0;i < input.length; i++)
{
ShowResults(input[i].value);
}
并将ShowResults函数更改为:
and change ShowResults function to:
function ShowResults(value) {
alert(value);
}
我们为什么需要这样做?
JavaScript中的某些对象看起来像一个数组,但不是一个.这通常意味着它们具有索引访问和length属性,但是没有数组方法.示例包括特殊的变量参数,DOM节点列表和字符串.类似于数组的对象和通用方法提供了处理类似数组的对象的技巧.
源
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
2019年10月7日更新
如今,使用ES6可以使用[...inputList].forEach
或Array.from(inputList)
UPDATE for 07.10.2019
Nowdays with ES6 you can use [...inputList].forEach
, or Array.from(inputList)
这篇关于如何遍历从getElementsByTagName返回的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!