removechild loop exits before finish

dom, javascript

Solution

The problem is that `items` is a live `NodeList`, 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 `NodeList` to an array first:

var items = [].slice.call(doc.getElementsByClassName('foo'));

The array size won't change when you delete the DOM elements.

Problem

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.

Original source