forEach does not access all elements in NodeList


forEach does not access all elements in NodeList



Since the forEach array method can now be called on a NodeList. I was wondering why if you make changes to the content of a childNodes NodeList while looping with forEach, forEach does not detect the changes.


forEach


NodeList


childNodes


forEach


forEach


grid.childNodes.forEach(function(tableRow, index, nodeList) {
tableRow.remove();
});



Here, i'm trying to loop through my table(grid) elements children and remove each children(tableRow) from the table. However, forEach never completely loop over every element, always leaving out one last tableRow to be removed.I think it has something to do with the childNodes NodeList being live, and the forEach not being able to properly follow it or something.


tableRow


forEach


tableRow


remove





What’s your relevant html? What’s the selector for grid?
– David Thomas
6 mins ago


grid





@DavidThomas const grid = document.querySelector("table");
– Obayanju Damilare
3 mins ago



const grid = document.querySelector("table");





You know you can just do grid.innerHTML = "", right?
– trincot
1 min ago


grid.innerHTML = ""





I’d hazard a guess that part of the problem is that the count of element children parentNode.children is not equal to the count of parentNode.childNodes.
– David Thomas
1 min ago



parentNode.children


parentNode.childNodes




1 Answer
1



This is because, at a lower level, the .forEach() is still keeping a count of the elements and, as you remove some, the count becomes inaccurate. For something like this, it's always better to use a counting loop and remove elements starting from the last index and working backwards. This will maintain a proper count for the duration of the loop.


.forEach()


for(i = grid.childNodes.length-1; i > -1; i--) {
grid.removeChild(grid.childNodes[i]);
});






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

iOS Top Alignment constraint based on screen (superview) height