For example: I want to create shortcut to element array
var $artifacts = $('.game-artifact');
but atm there aren't any elements with such class. Then comes some code, which adds elements. The question is if, after I add these elements will variable $artifacts still refer to them or it will remain null? If so, how I manage to assign a reference to function to a variable?
It will remain empty. You can update the reference once you have already added the elements:
// add elements
artifacts = $('.game-artifact');
Take a look at fiddle.
You can wrap it with function which will return current elements:
var artifacts = function(){
return $('.game-artifact');
};
var $artifacts = artifacts();
You should use .get() over accessing the array directly, to avoid out of bound errors.
var lists = $("body li");
console.log(lists.length); // returns 20
console.log(lists.get(25)); // returns undefined.
console.log(lists[25]); // Generates an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With