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?
views:
46answers:
2
Q:
When you use document.getElementsByTagName() in javascript do you get an array of all the elements?
+5
A:
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]
}
Nick Craver
2010-10-23 18:44:03
ok so could you reference one of the nodes by `nodelist[1]`?
chromedude
2010-10-23 18:45:41
@chromedude - yup, you sure can, it's 0-based so `1` would be the 2nd `<input>` element in the page.
Nick Craver
2010-10-23 18:46:13
@Nick ok thanks thats what I thought
chromedude
2010-10-23 18:46:58
+2
A:
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]
}
Felix Kling
2010-10-23 18:45:00
It's not an HTMLCollection, as you can't do `document.getElementsByTagName('input')["inputName"]`. HTMLCollection is an interface which NodeList doesn't implement.
Nick Craver
2010-10-23 18:51:24