This is one of the reasons why I almost always prefer $.each over for loops. For loops temp you into declaring variables inside the loop, but then they are still scoped to the function, not the block of the loop, even though it looks otherwise at first glance. Then if you want to, say, add a click handler inside the loop, any variables you reference will be set to the final element of the loop, which can cause some crazy problems. So, I actually like declaring variables outside of the loop, because it makes the scope of the variable more obvious. But just changing it to use $.each and then declaring the variables inside the new function makes things much clearer and less error-prone in my opinion.