views:

46

answers:

2

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?

+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
ok so could you reference one of the nodes by `nodelist[1]`?
chromedude
@chromedude - yup, you sure can, it's 0-based so `1` would be the 2nd `<input>` element in the page.
Nick Craver
@Nick ok thanks thats what I thought
chromedude
+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
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