JQuery assigns an element to a variable

For example: I want to create a shortcut for an array of elements

var $artifacts = $('.game-artifact'); 

but atm there are no such elements with such a class. Then code appears that adds the elements. The question is, after I add these elements, the $ artifact variables will still refer to them or will they remain empty? If so, how do I manage to assign a function reference to a variable?

+6
source share
3 answers

It will remain empty. You can update the link as soon as you have already added the elements:

 // add elements artifacts = $('.game-artifact'); 

Take a look at the fiddle .

+8
source

You can wrap it with a function that will return the current elements:

 var artifacts = function(){ return $('.game-artifact'); }; var $artifacts = artifacts(); 
+5
source

You should use .get () to directly access the array to avoid 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. 
0
source

Source: https://habr.com/ru/post/969959/


All Articles