Javascript无法按名称找到Div元素 [英] Javascript can't find Div Element by Name

查看:94
本文介绍了Javascript无法按名称找到Div元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天的这段代码令我感到吃惊,我很好奇发生了什么。



如果我指的是我知道的Div元素在页面中表单,甚至复制/粘贴确切的名称,使用getElementsByName以下可能找不到它。

  var coll = document.getElementsByName ( txtState); // coll将为空

如果我获取页面上的所有Div标签并遍历它们,在名称属性中,我可以找到正确的Div元素。

  var coll = document.getElementsByTagName(Div); 
for(var i = 0; i var el = coll [i];
if(el.name!= null){
if(el.name.length> 0){
if(el.name ==txtState){
警报( 实测值);
}
}
}
}

, 这是怎么回事?为什么Javascript无法获得特定元素?为什么我必须迭代集合?

解决方案

From 这里



在我们继续之前,我们应该消除一些书籍和互联网上的一些错误信息:根据W3C HTML 4.01规范,与某些人所说的相反,没有合法的方式来使用div或span等标签中的name属性。您必须将此属性的用法限制为输入,img,框架,iframe,表单,映射,参数,元,对象,A,select,applet,textarea或按钮等标记。

b
$ b

因此,name不是div的有效属性,这就是getElementsByName不起作用的原因。


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.

这篇关于Javascript无法按名称找到Div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆