Aryan
Aryan

Reputation: 23

Store Jquery object and access later?

I'm trying to store Jquery object into an array and access later to apply Jquery methods.

Something like:

var myArr = [];
myArr.push($('div#id1'));
myArr.push($('div#id2'));
$(myArr).show();

This is not working

Upvotes: 0

Views: 871

Answers (4)

Nicolas
Nicolas

Reputation: 1870

Another way, all JQueried ^^ :

var myElements = $('div#id1');
myElements = myElements.add('div#id2');

myElements.show();

To reverse the .add() you can use .not :

myElements = myElements.not('.clazz');

myElements.hide();

Upvotes: 0

George
George

Reputation: 36784

If you insist on storing your jQuery objects in an array, you will need to map that array to a new jQuery object before being able to call jQuery methods on it to affect your stored objects.

You can use jQuery's .map() for that:

var myArr = [];
myArr.push($('div#id1'));
myArr.push($('div#id2'));

$(myArr).map(function(){ return this.toArray(); }).show();

JSFiddle

Upvotes: 0

Etheryte
Etheryte

Reputation: 25310

Why are you storing the items in an array to begin with? If you only need to perform operations over multiple items you can simply do either of the following:

$('selector1, selector2').operation();
$('selector1').add('selector2').operation();

Upvotes: 0

Deleteman
Deleteman

Reputation: 8690

You're trying to execute the show method on the array passed to jQuery, not on each object, try something like this:

$.each(myArr, function(k, elem) {
  $(elem).show();
})

Upvotes: 1

Related Questions