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
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.
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');
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