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
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]);
}
}