GetElementsByTagName ("*") is always updated?

I 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?

Violin: http://jsfiddle.net/RL54Z/3/

I do not need to write childs=foo.getElementsByTagName("*");between the fifth and sixth lines in order to update childs.length.

How can it be?

+5
source share
2 answers

Most node lists in the DOM (for example, returned from getElementsBy*, querySelectorAlland Node.childNodes) are not simple arrays, but rather NodeListobjects. NodeListobjects usually live because changes to the document automatically propagate to the object NodeList. (An exception is a result querySelectorAllthat is not alive!)

, , NodeList a, a , a NodeList.

NodeList . , :

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 ( ), .

NodeLists Mozilla MDC.

+3

,

. , . , , DOM. , element.getElementsByTagName .

+3

All Articles