querySelectorAll和getElementsBy*方法返回什么?

2024-10-06 10:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

getElementsByClassName(以及类似的函数,如getElementsByTagNamequerySelectorAll)是否与getElementById工作相同,或者它们返回一个元素数组?

我问这个问题的原因是因为我正试图使用getElementsByClassName更改所有元素的样式。见下文。

//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';

//works
document.getElementById('myIdElement').style.size = '100px';

Tags: 函数元素sizestyle原因样式数组document
3条回答

您的getElementById()代码可以工作,因为id必须是唯一的,因此函数始终只返回一个元素(如果找不到元素,则返回null)。

但是,^{}^{}和其他getElementsBy*方法返回一个类似数组的元素集合。像使用实数数组一样遍历它:

var elems = document.getElementsByClassName('myElement');
for(var i = 0; i < elems.length; i++) {
    elems[i].style.size = '100px';
}

如果您喜欢较短的,可以考虑使用jQuery

$('.myElement').css('size', '100px');

您使用数组作为对象,getElementbyIdgetElementsByClassName是:

  • getElementbyId将返回一个Element object,如果找不到ID为的元素,则返回null
  • getElementsByClassName将返回一个live HTMLCollection,如果没有找到匹配的元素,则可能返回长度为0的

GetElementsByClass名称

The getElementsByClassName(classNames) method takes a string that contains an unordered set of unique space-separated tokens representing classes. When called, the method must return a live NodeList object containing all the elements in the document that have all the classes specified in that argument, having obtained the classes by splitting a string on spaces. If there are no tokens specified in the argument, then the method must return an empty NodeList.

https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyclassname

getElementById

The getElementById() method accesses the first element with the specified id.

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

在你的代码行:

1- document.getElementsByClassName('myElement').style.size = '100px';

将不会按预期工作,因为getElementByClassName将返回一个数组,并且数组将不会有style属性,您可以通过迭代访问每个element

这就是函数getElementById为您工作的原因,该函数将返回direct对象。因此,您将能够访问style属性。

以下描述摘自this page

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Tip: You can use the length property of the NodeList object to determine the number of elements with a specified class name, then you can loop through all elements and extract the info you want.

因此,作为参数,getElementsByClassName将接受类名。

如果这是您的HTML正文:

<div id="first" class="menuItem"></div>
<div id="second" class="menuItem"></div>
<div id="third" class="menuItem"></div>
<div id="footer"></div>

然后var menuItems = document.getElementsByClassName('menuItem')将返回上3个<div>的集合(不是数组),因为它们与给定的类名匹配。

然后,您可以使用以下命令在该节点(在本例中为<div>s)集合上迭代:

for (var menuItemIndex = 0 ; menuItems.length ; menuItemIndex ++) {
   var currentMenuItem = menuItems[menuItemIndex];
   // do stuff with currentMenuItem as a node.
}

有关元素和节点之间的差异的详细信息,请参阅this post

相关问题 更多 >