Removing elements from dom using queryselectorall, jquery, getelementsbyid, getelementsbyclassname

前端 未结 2 744
梦如初夏
梦如初夏 2021-01-21 23:24

I am writing a function for a library that takes an object of elements and removes it from the DOM. I have this working fine but was wondering if there is a way to do a single

2条回答
  •  借酒劲吻你
    2021-01-22 00:05

    Some of these functions return a live NodeList, which means that when you change the DOM, the collection changes immediately to reflect this. That's why a normal for loop doesn't work: when you remove elem[0], all the other entries in the collection move down. Then when you increment the index, you skip over the new elem[0].

    The easiest way to work around this is to loop from the high end down, instead of from 0 up.

    for (var j = elem.length-1; j >= 0; j--) {
        if (elem[j].parentNode) {
            elem[j].parentNode.removeChild(elem[j]);
        }
    }
    

提交回复
热议问题