Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i create an array that has multiple objects and then manipulate that array throughout my script?

I have created an array of jquery objects that I want to hide when a particular click event is triggered. Instead of looping through the contents of the same array for each click event can I transform the array into a single object or something that I can just attach a method on to?

I have a current fiddle here: http://jsfiddle.net/hd5qa/13/

Sorry if this sounds vague, I'm not sure how to best explain this.

Kyle

like image 812
styler Avatar asked Aug 20 '26 17:08

styler


2 Answers

Yes. You can create an empty jQuery object and then call .add on it for each element.

var all = $();
$.each(myArray, function(index, element) { all = all.add(element); });
// now you can use all to apply something to all of them
all.show();
all.hide();
// etc

See your updated demo on JSFiddle.

like image 197
icktoofay Avatar answered Aug 22 '26 07:08

icktoofay


Yes, there are a couple ways to do it. You can select them all at once:

var colors = $('#blue, #red, #green, #black, ...');

You can combine the individual collections into a single collection

var $blue = $('#blue');
var $red = $('#red');
var $green = $('#green');
var $black = $('#black');
var $purple = $('#purple');
var $orange = $('#orange');

var collection = $blue.add($red).add($green).add(.....

Or you can just give all the elements a class="color" attribute

var collection = $('.color');
like image 30
Sam Dufel Avatar answered Aug 22 '26 07:08

Sam Dufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!