getElementsByClassName
(以及类似的函数,如getElementsByTagName
和querySelectorAll
)是否与getElementById
工作相同,或者它们返回一个元素数组?
我问这个问题的原因是因为我正试图使用getElementsByClassName
更改所有元素的样式。见下文。
//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';
//works
document.getElementById('myIdElement').style.size = '100px';
您的
getElementById()
代码可以工作,因为id必须是唯一的,因此函数始终只返回一个元素(如果找不到元素,则返回null
)。但是,^{} 、^{} 和其他
getElementsBy*
方法返回一个类似数组的元素集合。像使用实数数组一样遍历它:如果您喜欢较短的,可以考虑使用jQuery:
您使用数组作为对象,
getElementbyId
和getElementsByClassName
是:getElementbyId
将返回一个Element object,如果找不到ID为的元素,则返回nullgetElementsByClassName
将返回一个live HTMLCollection,如果没有找到匹配的元素,则可能返回长度为0的GetElementsByClass名称
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyclassname
getElementById
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
在你的代码行:
将不会按预期工作,因为
getElementByClassName
将返回一个数组,并且数组将不会有style
属性,您可以通过迭代访问每个element
。这就是函数
getElementById
为您工作的原因,该函数将返回direct对象。因此,您将能够访问style
属性。以下描述摘自this page:
因此,作为参数,
getElementsByClassName
将接受类名。如果这是您的HTML正文:
然后
var menuItems = document.getElementsByClassName('menuItem')
将返回上3个<div>
的集合(不是数组),因为它们与给定的类名匹配。然后,您可以使用以下命令在该节点(在本例中为
<div>
s)集合上迭代:有关元素和节点之间的差异的详细信息,请参阅this post。
相关问题 更多 >
编程相关推荐