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?
2 Answers
Reset to default 6You 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]
}
本文标签:
版权声明:本文标题:When you use document.getElementsByTagName() in javascript do you get an array of all the elements? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744092364a2532270.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论