Search code examples
javascriptdomgetelementsbytagname

getElementsByTagName("*") always updated?


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?


Solution

  • 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.