Skip to content Skip to sidebar Skip to footer

Javascript Function Not Getting All Values First Time

I am trying to let the user upload a list of items to filter a search results table by. The problem is that not all rows that don't have values in the filter list are removed the f

Solution 1:

NodeLists (like you get with getElementsByTagName) are “live”, meaning they reflect the current state of the DOM at any time.

You are looping over the TR nodes, and then removing some of them while doing so. Lets say you are at index 1 in your loop (second loop iteration), and remove that node – all following nodes “slide up” one position, so that what formerly was the node with the index 2 has now index 1, and what was 3 is now 2, etc. But since you are also increasing your loop counter i by one each loop, in your next iteration you access the node that is now the one at index 2 (formerly 3) – and the node that was at position 2 before is not even processed any more.

Easiest solution for this problem: Loop over the nodes backwards, from rows.length - 1 to 0 (and decrease your loop counter variable then, obviously). Because if you remove a node at the end of the list, that does not affect the position of any nodes before it.


Post a Comment for "Javascript Function Not Getting All Values First Time"