谁能解释为什么 remove() 方法不能像我预期的那样工作。我想从文档中删除所有 img 元素。 遍历文档并删除所有图像,这就是我想要的,但这只删除了 2 张图像,为什么? 这是代码 JSBIN
HTML
<img src="http://www.lorempixel.com/50/50" alt="pic">
<img src="http://www.lorempixel.com/50/50/animals" alt="pic">
<img src="http://www.lorempixel.com/50/50/city" alt="pic">
JS
var imgElements = document.getElementsByTagName("img"); // HTMLCollection
for(var i=0; i<imgElements.length; i++) {
var img = imgElements[i];
img.remove();
}
最佳答案
关于这段代码,有两件事让我担心:
remove
是一种相对较新的 DOM 方法,它没有得到很好的支持。为了获得更好的支持,请使用img.parentNode.removeChild(img);
getElementsByTagName
返回一个liveNodeList
,因此当您从列表的开头删除元素时,所有其他元素上移。因此,如果列表有 5 个条目,并且您删除了i=0
元素,所有其他元素都会移动,现在有一个新i=0
元素(长度为4
)。您的循环将移动到i=1
,因此位于i=0
的元素(过去位于i=1
)不会不被处理。对于非实时
NodeList
,使用querySelectorAll('tagname')
(或者只是向后循环列表,从末尾移除)。或者使用Array.prototype.slice
将NodeList
转换为数组。querySelectorAll
受所有现代浏览器支持,IE8 也支持。
这是一个使用 querySelectorAll
的例子:
var imgElements = document.querySelectorAll("img"); // HTMLCollection
for(var i=0; i<imgElements.length; i++) {
var img = imgElements[i];
img.parentNode.removeChild(img);
}
或者只是倒数:
var imgElements = document.getElementsByTagName("img"); // HTMLCollection
for(var i=imgElements.length-1; i>=0; i--) {
var img = imgElements[i];
img.parentNode.removeChild(img);
}
或者使用Array.prototype.slice
:
var imgElements = Array.prototype.slice.call(document.getElementsByTagName("img"));
for(var i=0; i<imgElements.length; i++) {
var img = imgElements[i];
img.parentNode.removeChild(img);
}
关于javascript - 使用 DOM 方法删除图像元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889663/