getElementsByTagName(“*”) always updated?

时光毁灭记忆、已成空白 提交于 2019-12-10 04:57:45

问题


I have made this code:

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?

A fiddle: http://jsfiddle.net/RL54Z/3/

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

How can it be?


回答1:


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!)

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.

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]);
}

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.

Read more about NodeLists at the Mozilla MDC site.




回答2:


If you read the documentation you wouldn't be surprised

Returns a list of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself. The returned list is live, meaning that it updates itself with the DOM tree automatically. Consequently, there is no need to call several times element.getElementsByTagName with the same element and arguments.



来源:https://stackoverflow.com/questions/11271598/getelementsbytagname-always-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!