JavaScript nodelist hazards

If you grab a bunch of elements from your webpage with

document.getElementsByClassName

though the console may tell you the elements inhabit an array, they are actually in a NodeList. You can interact with a NodeList very similarly to an array, but unlike an array a NodeList is live-updated. This difference will probably only matter if you want to change the class of the elements, but then it can matter a lot. I grabbed a collection of divs by class name and tried to change their class name with a standard i=0 / i++ for loop. I couldn’t figure out why the for loop seemed to be skipping its middle iteration. Well, the answer is that when I changed the class name of the first entry of the list, it dropped out of the list, and the second iteration of the loop treated the new second element of the list, which was formerly the third element. The original second element was now the first and hence did not get treated. If I’d had more than three divs with the relevant class name I would have seen the for loop skip every other one.

Solutions:
A) convert the NodeList to an array (probably unnecessary).
B) Back through your list:

for (var i = listName.length - 1 ; i >= 0 ; i--) { }

C) Use jQuery (specifics still to be determined).

Leave a Reply

Your email address will not be published. Required fields are marked *