最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - removechild loop exits before finish - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Jun 21, 2012 at 23:14 Felix Kling 817k180 gold badges1.1k silver badges1.2k bronze badges asked Jun 21, 2012 at 23:05 ama2ama2 2,6813 gold badges22 silver badges29 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

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

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

This works because the item removed from the list each iteration is the last item in the list, therefore not affecting earlier items.

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

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.

发布评论

评论列表(0)

  1. 暂无评论