This code surprised me yesterday and I'm curious about what was going on.
If I refer to a Div element that I know is on the page in a Form, even copy/pasting the exact name, using getElementsByName the following could would not find it.
var coll = document.getElementsByName("txtState"); //coll will be null
If I get all the Div tags on the page and iterate through them looking at the name property I could find the correct Div element.
var coll = document.getElementsByTagName("Div"); for (var i = 0; i < coll.length; i++) { var el= coll[i]; if (el.name != null) { if (el.name.length > 0) { if (el.name == "txtState") { alert("Found"); } } } }
So, what's up? Why is Javascript blind to getting the specific element? Why do I have to iterate over the collection?