Skip to content Skip to sidebar Skip to footer

Why Jquery's Each Loop’s Function Saves A Reference To An Element Object

Recently I discovered that jQuery saves a variable in an each loop’s function, if it has been set with a jQuery object reference. For example below $elem value stays the same dur

Solution 1:

Does anyone have an idea why $elem refers to the first div during second and third iteration of each method?

Because you set global variable $elem in the first iteration and this variable never changes later. So in the loop and after loop is complete this variable will point to the first div jQuery object.

Never forget to declare variables with var keyword. Undeclared but initialized variables become global variables. As you can see it can lead to confusion and errors.

Solution 2:

This is because a varialbe does not have a lexical scope by default. If it was declared as

var$elem

instead, it would be reset to undefined each time the function is run.

See the variable statement developer page for more information.

Post a Comment for "Why Jquery's Each Loop’s Function Saves A Reference To An Element Object"