Showing posts with label getElementsByTagName removeChild. Show all posts
Showing posts with label getElementsByTagName removeChild. Show all posts

Wednesday, August 5, 2009

Javascript Array from getElementsByTagName is LIVE!

The array returned by getElementsByTagName() function is LIVE!

What I mean by LIVE is that as you traverse the array and invoke changes to the DOM, the items in the array itself can change automatically! Here's an example:

var inputEls = divEl.getElementsByTagName('input');
for (var j=0; j < inputEls.length; j++) {
alert('inputEls length='+inputEls.length);
var inputEl = inputEls[j];
inputEl.parentNode.removeChild(inputEl);
}

What you'll actually see is that the length of the array automatically decreases with each iteration because I am removing those elements from the DOM.

To work around this issue I had to traverse the array backwards:

for(var i=inputEls.length-1;i>=0; i--) {

}