I have the following piece of code that finds all elements in the document with classname foo and then removes them all
function(doc) {
var items = doc.getElementsByClassName('foo');
alert(items.length);
if(items.length>0) {
for(var i=0;i<items.length;i++) {
alert(i);
doc.body.removeChild(items[i]);
}
}
Forexample, the items.length is 3 and the function exits after running one loop and when the length is 8 it exits at 3. Any help would be greatly appreciated. Also, when I run the function again and again it does eventually remove all elements.
The problem is that
itemsis a liveNodeList, i.e. whenever you access a property of the list (items.length), the list is reevaluated (elements are searched again).Since you delete elements in the meantime, the list becomes shorter, but you keep the index.
You could convert the
NodeListto an array first:The array size won’t change when you delete the DOM elements.