admin 管理员组

文章数量: 1086019

I have this document.getElementsByTagName('input') to get all the <input> elements on the page. will this result in an array that I can put a for loop through?

I have this document.getElementsByTagName('input') to get all the <input> elements on the page. will this result in an array that I can put a for loop through?

Share Improve this question asked Oct 23, 2010 at 18:42 chromedudechromedude 4,31216 gold badges69 silver badges96 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can use a for loop, but it's not an Array that's returned, it's a NodeList, for example:

var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++) {
  //do something with inputs[i]
}

No, it is not an array, it is an HTML collection NodeList. But the behave like arrays so you can use a normal for loop to traverse it.

The catch here is that the collection is live which means some methods/attributes will make the collection to update (meaning evaluate) again. One of these is length, so for performance reasons, you should retrieve this value once, e.g.:

for(var i = 0, l = elements.length; i < l; i++) {
    // so something with elements[i]
}

本文标签:

Error[2]: Invalid argument supplied for foreach(), File: /www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm, Line: 58
File: /www/wwwroot/roclinux.cn/tmp/route_read.php, Line: 205, include(/www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm)
File: /www/wwwroot/roclinux.cn/tmp/index.inc.php, Line: 129, include(/www/wwwroot/roclinux.cn/tmp/route_read.php)
File: /www/wwwroot/roclinux.cn/index.php, Line: 29, include(/www/wwwroot/roclinux.cn/tmp/index.inc.php)