javascript - getElementsByTagName("*") always updated? -
i have made 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 write childs=foo.getelementsbytagname("*");
between fifth , sixth line childs.length
updated.
how can be?
most lists of nodes in dom (e.g. returned getelementsby*
, queryselectorall
, , node.childnodes
) not simple arrays rather nodelist
objects. nodelist
objects "live", in changes document automatically propagated nodelist
object. (an exception result queryselectorall
, not live!)
so can see in example, if retrieve nodelist of a
elements, add a
element document, a
appear in nodelist object.
this why unsafe iterate through nodelist while making changes document @ same time. e.g., code behave in surprising ways:
var nodelista = document.getelementsbytagname('a'); (var i=0; i<nodelista.length; ++i) { // unsafe: don't this! nodelista[i].parentnode.removechild(nodelista[i]); }
what happen end skipping elements! either iterate backwards end of nodelist, or copy nodelist plain array (which not update) , work that.
read more nodelists @ mozilla mdc site.
Comments
Post a Comment