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.
source share