Javascript querySelectorAll 和 getElementsBy* 方法返回什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10693845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What do querySelectorAll and getElementsBy* methods return?
提问by dmo
Do getElementsByClassName
(and similar functions like getElementsByTagName
and querySelectorAll
) work the same as getElementById
or do they return an array of elements?
DO getElementsByClassName
(等类似的功能getElementsByTagName
和querySelectorAll
)的工作一样getElementById
,还是他们返回元素的数组?
The reason I ask is because I am trying to change the style of all elements using getElementsByClassName
. See below.
我问的原因是因为我试图使用getElementsByClassName
. 见下文。
//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';
//works
document.getElementById('myIdElement').style.size = '100px';
回答by ThiefMaster
Your getElementById()
code works since IDs have to be unique and thus the function always returns exactly one element (or null
if none was found).
您的getElementById()
代码可以工作,因为 ID 必须是唯一的,因此该函数始终只返回一个元素(或者null
如果没有找到)。
However, getElementsByClassName()
, querySelectorAll()
, and other getElementsBy*
methods return an array-like collection of elements. Iterate over it like you would with a real array:
但是,getElementsByClassName()
、querySelectorAll()
和其他getElementsBy*
方法返回一个类似数组的元素集合。像使用真正的数组一样迭代它:
var elems = document.getElementsByClassName('myElement');
for(var i = 0; i < elems.length; i++) {
elems[i].style.size = '100px';
}
If you prefer something shorter, consider using jQuery:
如果您更喜欢更短的内容,请考虑使用jQuery:
$('.myElement').css('size', '100px');
回答by Alvaro Joao
You are using a array as an object, the difference between getElementbyId
and
getElementsByClassName
is that:
您使用的阵列为对象,之间的差getElementbyId
和
getElementsByClassName
是:
getElementbyId
will return an Element objector null if no element with the ID is foundgetElementsByClassName
will return a live HTMLCollection, possibly of length 0 if no matching elements are found
getElementbyId
如果没有找到具有 ID 的元素,将返回一个Element 对象或 nullgetElementsByClassName
将返回一个实时的 HTMLCollection,如果没有找到匹配的元素,长度可能为 0
getElementsByClassName
getElementsByClassName
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 liveNodeList
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.
该
getElementsByClassName(classNames)
方法采用一个字符串,该字符串包含一组无序的、以空格分隔的唯一标记表示类。调用时,该方法必须返回一个NodeList
包含文档中所有元素的活动 对象,这些元素具有该参数中指定的所有类,通过在空格上拆分字符串获得类。如果参数中没有指定令牌,则该方法必须返回一个空的 NodeList。
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyclassname
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyclassname
getElementById
getElementById
The getElementById() method accesses the first element with the specified id.
getElementById() 方法访问具有指定 id 的第一个元素。
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
in your code the lines:
在您的代码中:
1- document.getElementsByClassName('myElement').style.size = '100px';
1- document.getElementsByClassName('myElement').style.size = '100px';
will NOTwork as expected, because the getElementByClassName
will return an array, and the array will NOThave the style
property, you can access each element
by iterating through them.
将不符合市场预期,因为工作getElementByClassName
会返回一个数组,数组将不具有style
属性,您可以访问每个element
通过他们的迭代。
That's why the function getElementById
worked for you, this function will return the direct object. Therefore you will be able to access the style
property.
这就是该函数getElementById
对您有用的原因,该函数将返回直接对象。因此,您将能够访问该style
属性。
回答by kind user
ES6provides Array.from()
method, which creates a new Array instance from an array-like or iterable object.
ES6提供了Array.from()
方法,该方法从类数组或可迭代对象创建一个新的 Array 实例。
let boxes = document.getElementsByClassName('box');
Array.from(boxes).forEach(v => v.style.background = 'green');
console.log(Array.from(boxes));
.box {
width: 50px;
height: 50px;
margin: 5px;
background: blue;
display: inline-block;
}
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
As you can see inside the code snippet, after using Array.from()
function you are then able to manipulate over each element.
正如您在代码片段中看到的那样,在使用Array.from()
函数之后,您就可以对每个元素进行操作。
The same solution using jQuery
.
使用相同的解决方案jQuery
。
$('.box').css({'background':'green'});
.box {
width: 50px;
height: 50px;
margin: 5px;
background: blue;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
回答by remdevtec
The following description is taken from 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() 方法返回文档中具有指定类名的所有元素的集合,作为 NodeList 对象。
NodeList 对象表示节点的集合。可以通过索引号访问节点。索引从 0 开始。
提示:您可以使用 NodeList 对象的 length 属性来确定具有指定类名的元素的数量,然后您可以遍历所有元素并提取所需的信息。
So, as a parameter getElementsByClassName
would accept a class name.
因此,作为参数getElementsByClassName
将接受类名。
If this is your HTML body:
如果这是您的 HTML 正文:
<div id="first" class="menuItem"></div>
<div id="second" class="menuItem"></div>
<div id="third" class="menuItem"></div>
<div id="footer"></div>
then var menuItems = document.getElementsByClassName('menuItem')
would return a collection (not an array) of the 3 upper <div>
s, as they match the given class name.
thenvar menuItems = document.getElementsByClassName('menuItem')
将返回 3 个 upper<div>
的集合(不是数组),因为它们与给定的类名匹配。
You can then iterate over this nodes (<div>
s in this case) collection with:
然后,您可以使用以下命令迭代此节点(<div>
在本例中为 s)集合:
for (var menuItemIndex = 0 ; menuItems.length ; menuItemIndex ++) {
var currentMenuItem = menuItems[menuItemIndex];
// do stuff with currentMenuItem as a node.
}
Please refer to this postfor more on differences between elements and nodes.
回答by Thielicious
In Other Words
换句话说
document.querySelector()
selects only the first oneelement of the specified selector. So it doesn't spit out an array, it's a single value. Similar todocument.getElementById()
which fetches ID-elements only, since IDs have to be unique.document.querySelectorAll()
selects allelements with the specified selector and returns them in an array. Similar todocument.getElementsByClassName()
for classes anddocument.getElementsByTagName()
tags only.
document.querySelector()
只选择指定选择器的第一个元素。所以它不会吐出一个数组,它是一个单一的值。类似于document.getElementById()
只获取 ID 元素,因为 ID 必须是唯一的。document.querySelectorAll()
选择具有指定选择器的所有元素并在数组中返回它们。仅类似于document.getElementsByClassName()
类和document.getElementsByTagName()
标签。
Why use querySelector?
为什么要使用 querySelector?
It's used merely for the sole purpose of ease and brevity.
它仅用于简单和简洁的唯一目的。
Why use getElement/sBy?*
为什么要使用 getElement/sBy?*
Faster performance.
更快的性能。
Why this performance difference?
为什么会有这种性能差异?
Both ways of selection has the purpose of creating a NodeListfor further use.
querySelectorsgenerates a static NodeList with the selectors thus it must be first created from scratch.
getElement/sBy*immediately adapts the existing live NodeList of the current DOM.
两种选择方式的目的都是创建一个NodeList以供进一步使用。
querySelectors生成一个带有选择器的静态 NodeList,因此它必须首先从头开始创建。
getElement/sBy*立即适应当前 DOM 的现有活动 NodeList。
So, when to use which method it's up to you/your project/your device.
因此,何时使用哪种方法取决于您/您的项目/您的设备。
Infos
资讯
回答by Irina Mityugova
/*
* To hide all elements with the same class,
* use looping to reach each element with that class.
* In this case, looping is done recursively
*/
const hideAll = (className, i=0) => {
if(!document.getElementsByClassName(className)[i]){ //exits the loop when element of that id does not exist
return;
}
document.getElementsByClassName(className)[i].style.visibility = 'hidden'; //hide element
return hideAll(className, i+1) //loop for the next element
}
hideAll('appBanner') //the function call requires the class name
回答by Sergey
You could get a single element by running
您可以通过运行获得单个元素
document.querySelector('.myElement').style.size = '100px';
but it's going to work for the first element with class .myElement.
但它适用于类 .myElement 的第一个元素。
If you would like apply this for all elements with the class I suggest you to use
如果您想将此应用于该类的所有元素,我建议您使用
document.querySelectorAll('.myElement').forEach(function(element) {
element.style.size = '100px';
});
回答by atilkan
It returns Array-like list.
它返回类似数组的列表。
You make that an Array as example
你把它作为一个数组作为例子
var el = getElementsByClassName("elem");
el = Array.prototype.slice.call(el); //this line
el[0].appendChild(otherElem);
回答by Matas Vaitkevicius
With ES5+ (any browsed nowadays - 2017) you should be able to do
使用 ES5+(现在任何浏览过的 - 2017 年),您应该能够做到
[].forEach.call(document.getElementsByClassName('answer'), function(el) {
el.style.color= 'red';
});