removechild loop exits before finish

前端 未结 2 1920
攒了一身酷
攒了一身酷 2020-12-03 16:00

I have the following piece of code that finds all elements in the document with classname foo and then removes them all

        function(doc) {
            v         


        
相关标签:
2条回答
  • 2020-12-03 16:45

    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.

    0 讨论(0)
  • 2020-12-03 17:01

    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 讨论(0)
提交回复
热议问题