removechild循环在完成之前退出 [英] removechild loop exits before finish
问题描述
我有以下代码可以在文档中找到classname foo的所有元素,然后删除它们全部
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]);
}
}
例如,items.length是3,函数运行一个循环后退出,当长度为8时,它退出3.任何帮助将不胜感激。此外,当我一次又一次地运行该函数时,它最终会删除所有元素。
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.
推荐答案
问题是项目
是一个 / strong> NodeList
,即每当您访问列表的属性( items.length
)时,重新评估列表(元素再次搜索)
由于您在此期间删除元素,列表变短,但您保留索引。
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.
您可以将 NodeList
转换为数组:
var items = [].slice.call(doc.getElementsByClassName('foo'));
删除DOM元素时,数组大小不会改变。
The array size won't change when you delete the DOM elements.
这篇关于removechild循环在完成之前退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!