It appears that the issue is occurring only with every second picture rather than all of them.
Typically, this pattern indicates a problem with destructive iteration.
If we assume that the function cvi_instant.add
is replacing the element named pic
with different elements, then here's what could be happening:
getElementsByName
returns a 'live' NodeList, meaning it gets updated whenever there are changes in the DOM. So if it originally had five elements and after calling cvi_instant.add
, it now has only four - the first node is removed and nodes 1 through 4 shift down to positions 0 through 3.
As you loop through again, i++
increments, which means you're now accessing element 1, but this was originally element 2! You've skipped over the original element 1, causing the skipping pattern to continue until the end of the now shortened list.
When you alter a list while iterating through it, you run into such issues. In fact, if the process within the loop adds elements to the list, you might even end up in an endless loop!
A quick fix is to iterate the loop backwards. This way, starting with the last element avoids any skipping issues:
var e= document.getElementsByName("pic");
for (var i= e.length; i-->0;) {
cvi_instant.add(e[i], { shadow: 75, shade: 10 });
}
Another straightforward solution, especially when you consistently remove elements from the list in each call, is:
var e= document.getElementsByName("pic");
while (e.length>0) {
cvi_instant.add(e[0], { shadow: 75, shade: 10 });
}
The most versatile solution comes into play when your loop body can perform any action on the list, like adding new elements named pic
at the beginning or removing elements from the middle. Although slightly slower, making a static copy of the list guarantees safety:
function Array_fromList(l) {
var a= [];
for (var i= 0; i<l.length; i++)
a.push(l[i]);
return a;
}
var e= Array_fromList(document.getElementsByName("pic"));
for (var i= 0; i<e.length; i++) {
cvi_instant.add(e[i], { shadow: 75, shade: 10 });
}