Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign an element to variable?

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?

like image 742
Selenir Avatar asked May 28 '14 12:05

Selenir


3 Answers

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.

like image 124
mareckmareck Avatar answered Nov 01 '22 05:11

mareckmareck


You can wrap it with function which will return current elements:

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

var $artifacts = artifacts();
like image 6
hsz Avatar answered Nov 01 '22 07:11

hsz


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.
like image 1
beliha Avatar answered Nov 01 '22 06:11

beliha