Exitchild loop ends before completion

I have the following code snippet that finds all the elements in a document with class name 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]); } } 

For example, item.length is 3, and the function will exit after starting one cycle, and when the length is 8, it will exit 3. Any help would be greatly appreciated. Also, when I run the function again and again, it ultimately deletes all the elements.

+4
source share
2 answers

The problem is that items is a live NodeList , i.e. whenever you access the list property ( items.length ), the list is reevaluated (items are searched again).
As you delete items in the meantime, the list gets shorter, but you keep the index.

You can first convert the NodeList to an array:

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

The size of the array will not change when deleting DOM elements.

+7
source

Your problem is that the NodeList returned by getElementsByClassName() is live. Either convert it to an array first, as Felix suggests, or repeat it:

 var items = doc.getElementsByClassName('foo'); var i = items.length; while (i--) { items[i].parentNode.removeChild(items[i]); } 

This works because an item removed from the list, each iteration is the last item in the list, so it does not affect the previous items.

I also changed doc.body to items[i].parentNode for more generality if you need to deal with elements that are not direct children of the <body> element.

+11
source

All Articles