javascript dom getElementsByName问题?

在使用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例外?

阅读 5k
5 个回答

谢邀~

这个getElementsByName就是document特有的方法,
并不同与题主所说的其他方法,
其他方法适用于element
clipboard.png

clipboard.png

而且兼容性不好.

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.

传送门: https://developer.mozilla.org...

console.log('document instanceof HTMLDocument', document instanceof HTMLDocument);
console.log('document.body instanceof Element',document.body instanceof Element);
console.log(HTMLDocument.prototype.getElementsByName);
console.log(Element.prototype.getElementsByName);

clipboard.png

通过这两句我们可以看到document和其他的dom元素的构造函数是不同,这就决定了他们原型中的属性不同。
getElementsByNameHTMLDocument的原型对象中的方法,所以才会出现你说的情况。

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不一定是所有元素都可以有的属性吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题