javascript dom getElementsByName问题?
PHP中文网
PHP中文网 2017-04-11 12:07:34
[JavaScript讨论组]

在使用getElementsByName过程中发现,该函数只能在document下被调用。而其它的,类似getElementsByClassName,TagName,id可以被元素使用。
var form=document.getElementsByTagName("form")[0];
var obj=form.getElementsByTagName("button")[0];//有效

var form=document.getElementsByTagName("form")[0];
//假设有个button name="btn";
var obj=form.getElementsByName("btn")[0];//无效

通过name获得对象只能是这样:document.getElementsByName("btn")[0];

百度了一下说因为getElementsByName是document的方法,但是其余的获取方式也是document对象的方法啊。为什么其他的可以而getElementsByName例外?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(1)
高洛峰
The name attribute is only applicable to (X)HTML documents. The method returns a live NodeList Collection that contains all elements

with a given value for the name attribute, such as <meta> or <object>
or even if name is placed on elements which do not support a name
attribute at all.


The getElementsByName method works differently in different browsers. In IE & Opera, getElementsByName() method will also return

elements that have an id attribute with the specified value. so you
should be careful not to use the same string as both a name and an ID.

Document.getElementsByName()

估计是因为name不一定是所有元素都可以有的属性吧。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号