i have the following javascript below after i finish an ajax query
all of my images have name=”pic”
<script type="text/javascript">
function done() {
var e = document.getElementsByName("pic");
alert(e.length);
for (var i = 0; i < e.length; i++) {
cvi_instant.add(e[i], { shadow: 75, shade: 10 });
}
}
my goal is to apply an image border around using this library:
http://www.netzgesta.de/instant/
the problem is that for some reason this works but it only seem to apply to every other picture instead of every one. any clue why the code above would skip every other element??
EDIT: I added an alert in the loop and it does correctly go 0, 1,2,3,4,5,6 . .
for (var i = 0; i < e.length; i++)
{
alert(i);
cvi_instant.add(e[i], { shadow: 75, shade: 10 });
}
That’s a classic sign of destructive iteration.
Consider what happens if, as I’m guessing, the function
cvi_instant.addreplaces the element namedpicwith some other element or elements.getElementsByNamereturns a ‘live’ NodeList: it is kept up to date every time you make a change to the DOM. So if it had five elements before, after your call tocvi_instant.addit now contains only four: the first node is gone and nodes 1–4 have moved down to positions 0–3.Now you go around the loop again.
i++, so we’re looking at element 1. But element 1 is now what was originally element 2! We skipped the original element 1, and we will continue skipping every other element until we reach the end of the (now half as long) list.Altering a list at the same time as iterating it causes this kind of problem. If the process inside the iteration actually adds elements to the list you can even get an infinite loop!
The quick fix is to iterate the loop backwards. Now you do the last element first, leaving all the other elements in their original positions and causing no skipping:
Another simple solution if you know you’re always going to be removing the element from the list on each call is:
The most general solution is needed when your loop body can do anything to the list, such as inserting new elements named
picat the start of the document or removing other elements from the middle. It is slightly slower but always safe to make a static copy of the list to work from: