getElementsByTagName(“ *”)总是更新吗? [英] getElementsByTagName("*") always updated?

查看:112
本文介绍了getElementsByTagName(“ *”)总是更新吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码:

var foo=document.createElement("div");

var childs=foo.getElementsByTagName("*");

console.log(childs.length);//0 OK

var a=document.createElement("a");

foo.appendChild(a);

console.log(childs.length);//1 WTF?

小提琴: http://jsfiddle.net/RL54Z/3/

我不必写 childs = foo.getElementsByTagName ( *); 在第五行和第六行之间,以便更新 childs.length

I don't have to write childs=foo.getElementsByTagName("*"); between the fifth and the sixth line so that childs.length is updated.

怎么可能?

推荐答案

DOM中大多数节点列表(例如从<$ c返回) $ c> getElementsBy * , querySelectorAll Node.childNodes )不是简单的数组而是 NodeList 对象。 NodeList 对象通常是活动的,因为对文档的更改会自动传播到 Nodelist 对象。 (一个例外是 querySelectorAll 的结果,它是 not 实时的!)

Most lists of nodes in the DOM (e.g. returned from getElementsBy*, querySelectorAll, and Node.childNodes) are not simple Arrays but rather NodeList objects. NodeList objects are usually "live", in that changes to the document are automatically propagated to the Nodelist object. (An exception is the result from querySelectorAll, which is not live!)

因此,如您在示例中所看到的,如果检索所有 a 元素的NodeList,则添加另一个 a 元素在文档中, a 将出现在您的NodeList对象中。

So as you can see in your example, if you retrieve a NodeList of all a elements, then add another a element to the document, that a will appear in your NodeList object.

这就是为什么不安全地遍历同时更改文档的NodeList。例如,此代码的行为方式会令人惊讶:

This is why it is unsafe to iterate through a NodeList while making changes to the document at the same time. E.g., this code will behave in surprising ways:

var NodeListA = document.getElementsByTagName('a');

for (var i=0; i<NodeListA.length; ++i) {
   // UNSAFE: don't do this!
   NodeListA[i].parentNode.removeChild(NodeListA[i]);
}

会发生什么,您最终将跳过元素!从NodeList的末尾向后迭代,或者将NodeList复制到一个普通的数组(不会更新),然后使用它。

What will happen is you will end up skipping elements! Either iterate backwards from the end of the NodeList, or copy the NodeList to a plain Array (which will not update) and then work with that.

有关更多信息,请参见 Mozilla MDC网站

Read more about NodeLists at the Mozilla MDC site.

这篇关于getElementsByTagName(“ *”)总是更新吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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