Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

javascript - removechild loop exits before finish

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...