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?
From here:
Before we continue, we should dispel some of the misinformation in a few books and on the Internet: Contrary to what some have said, there is no legal way to use the name attribute from such tags as div or span, according to the W3C HTML 4.01 specs. You must confine the usage of this attribute to such tags as input, img, frame, iframe, form, map, param, meta, object, A, select, applet, textarea, or button.
So, ‘name’ is not a valid attribute for a div, which is why getElementsByName won’t work.