Javascript can't find Div Element by Name

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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?

回答1:

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.



回答2:

I've always relied on using getElementById('SomeId') and ensured the ID property of the DIV tag is set.

Try this with your DIV's, and it should resolve your javascript problem.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!