getElementsByClassName和querySelectorAll之间的区别? [英] Difference between getElementsByClassName and querySelectorAll?
问题描述
根据我的理解,
var elems = document.querySelectorAll(".class");
var elems = document.getElementsByClassName("class");
应返回相同的内容。但是,当我尝试使用
should return the same things. However, when I try to remove the class from all the elements using
for (var i = 0; i < elems.length; ++i)
elems[i].className = "";
我得到不同的结果。 querySelectorAll
从所有元素中成功删除了类,但 getElementsByClassName
仅从大约一半的元素中删除了类。
I get different results. querySelectorAll
successfully removes the classes from all the elements, but getElementsByClassName
only removes the classes from about half the elements.
发生了什么事?
推荐答案
querySelectorAll
不返回实时DOM元素。对基础文档结构的后续更改不会反映在 querySelectorAll
返回的NodeList对象中。这意味着该对象将包含创建列表时文档中匹配的Element节点的列表。
querySelectorAll
doesn't return live DOM elements. Subsequent changes to the structure of the underlying document won't be reflected in the NodeList object returned by querySelectorAll
. This means that the object will instead contain a list of matching Element nodes that were in the document at the time the list was created.
getElementsByClassName
返回实时DOM元素。对这些DOM元素所做的任何后续更改都将反映在列表中。
getElementsByClassName
returns live DOM elements. Any subsequent change made to those DOM elements would be reflected in the list.
这篇关于getElementsByClassName和querySelectorAll之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!