document.getElementsByClassName()数组中元素的顺序 [英] Order of elements in document.getElementsByClassName() array

查看:535
本文介绍了document.getElementsByClassName()数组中元素的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在打电话

document.getElementsByClassName('fastSearch', 'document.forms'); 

在HTML上的我的js代码中.

in my js code on html.

每次调用都会得到相同顺序的元素吗?

Will I get the same order of elements everytime I call?

推荐答案

是的,您将遵循一致的实现,但是

Yes, you will, on conforming implementations, but what it returns is not an array, it's an HTMLCollection. The results will be in document order (top-down, depth-first traversal — which is a fancy way of saying, what it looks like when you look at the markup :-) ).

例如,使用此文档:

<div id="d1" class="a">
    <div id="d2" class="a">
        <div id="d3" class="a"></div>
    </div>
    <div id="d4" class="a"></div>
</div>
<div id="d5" class="a"></div>

getElementsByClassName("a")将可靠地按以下顺序列出它们:d1,d2,d3,d4,d5.

getElementsByClassName("a") will reliably list them in order: d1, d2, d3, d4, d5.

请注意,某些较旧的浏览器(尤其是IE8)不支持getElementsByClassName.支持它的所有模糊的现代方法还支持更常用的 querySelectorAll (它支持基于任何CSS选择器的查询),(反过来)在IE8中也是 .

Note that getElementsByClassName is not supported by some older browsers, notably IE8. Everything vaguely-modern that supports it also supports the more generally-useful querySelectorAll (which supports a query based on any CSS selector), which (perversely) is in IE8 as well.

其他说明:

  • 在符合标准的实现中,getElementsByClassName返回一个 live HTMLCollection,这意味着,如果添加,删除或更改元素,则现有的集合将被更新.这可能有用且强大,或者令人惊讶,这取决于您在做什么.
  • querySelectorAll返回快照 NodeList ,例如不是实时的HTMLCollection.
  • On a conforming implementation, getElementsByClassName returns a live HTMLCollection, which means that if you add, remove, or change elements, the collection you already have will be updated. That can be useful and powerful, or surprising, depending on what you're doing with it.
  • querySelectorAll returns a snapshot NodeList, e.g., not a live HTMLCollection.

示例:

var byClassName = document.getElementsByClassName("a");
var bySelector = document.querySelectorAll(".a");
console.log("Before adding another one:");
console.log("byClassName.length = " + byClassName.length);
console.log("bySelector.length = " + bySelector.length);
var div = document.createElement("div");
div.className = "a"
document.body.appendChild(div);
console.log("AFTER adding another one:");
console.log("byClassName.length = " + byClassName.length);
console.log("bySelector.length = " + bySelector.length);

<div id="d1" class="a">
  <div id="d2" class="a">
    <div id="d3" class="a"></div>
  </div>
  <div id="d4" class="a"></div>
</div>
<div id="d5" class="a"></div>

这篇关于document.getElementsByClassName()数组中元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆