“订单”如何可靠在查询的节点列表中 [英] How reliable is "order" in queried NodeLists

查看:169
本文介绍了“订单”如何可靠在查询的节点列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这个话题已经有一段时间了。有关方法如下:

I am wondering about this topic for quite a while. The methods in question are the following:


  • getElementsByTagName

  • getElementsByClassName

  • getElementsByName

  • querySelectorAll

  • getElementsByTagName
  • getElementsByClassName
  • getElementsByName
  • querySelectorAll

据我所知,方法是唯一能够返回冻结或生活的方法。 NodeLists 。对于某些方法,订单由W3C规范定义。例如, http://www.w3.org NodeLists 返回的 querySelectorAll

As far as I know, those DOM methods are the only methods which are able to return frozen or live NodeLists. For some of those methods, order is defined by W3C spec. For instance, http://www.w3.org writes the following for NodeLists returned by querySelectorAll


querySelectorAll()方法Document,DocumentFragment和
元素接口必须以
文件顺序返回包含上下文节点子树中所有
匹配元素节点的NodeList。如果没有匹配的节点,方法必须返回
一个空的NodeList。

The querySelectorAll() methods on the Document, DocumentFragment, and Element interfaces must return a NodeList containing all of the matching Element nodes within the subtrees of the context node, in document order. If there are no matching nodes, the method must return an empty NodeList.

然而,我找不到类似的清除我提到的其他方法的规格。我的问题是:

However, I couldn't find similar clear specifications for the the other methods I mentioned. My questions here are:


  • 是否有定义的顺序(很可能是文档顺序)的结果

  • 这些规范的可靠性和跨浏览器的执行情况

  • is there a defined order (most likely document order) for the results ?
  • how reliable and cross-browser implemented are those specs ?

绝对清楚:

<div>this</div>
<div>is</div>
<div>a demo</div>

// is this always guaranteed to be "<div>is</div>"
document.querySelectorAll('div')[1]


推荐答案

是。所有这些都是文档顺序/树顺序。

Yes. All of them are in document order / tree order.

  • getElementsByName (DOM Level-2-HTML) returns a NodeList
  • querySelectorAll (Selectors API) returns a NodeList "in document order"
  • getElementsByTagName (DOM) returns a HTMLCollection
  • getElementsByClassName (DOM) returns a HTMLCollection

HTMLCollection s NodeList s 都被指定为具有

HTMLCollections and NodeLists are both specified to have


元素是按照树顺序进行排序。

当这些通过indizes访问。

when those are accessed via indizes.

我认为那些规范(即使链接的版本可能更新比一些实现)被所有浏览器可靠地实现,主要是因为树顺序是最合乎逻辑且易于编码的。但是,您可能需要注意,某些浏览器可能会返回由不同元素组成的列表,因为它们的节点匹配不同。确定元素的名称时,我可以想到一些怪癖。

I think that those specs (even though the linked versions might be newer than some implementations) are reliably implemented by all browsers, mostly because tree order is the most logical and easy-to-code one. Yet, you might need to watch out that some browsers might return lists consisting of different elements because their matching of nodes differs. I could think of some quirks when determining the name of an element.

这篇关于“订单”如何可靠在查询的节点列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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