2

I'm not sure if "cached" is a correct term for this one. Maybe I should use "instantiated" instead. However, say I want to "cache" several objects, to save some resources:

var $foo = $("#foo"),
$bar = $("#bar");

Now, if I want to hide them, can I use a one-liner instead of:

$foo.hide();
$bar.hide();

I reckon that this one is quite simple (read: "stupid"), but hey... I can't figure it out all by myself...

aL3xa
  • 35,415
  • 18
  • 79
  • 112

5 Answers5

4

You can also use .add() to roll up a bunch of jQuery objects and selectors:

$foo.add( $bar ).add('.someclass').add( $other_objects_or_selectors ).hide();
Ken Redler
  • 23,863
  • 8
  • 57
  • 69
1

you can use something like this:

$.each([$foo, $bar], function(i, v) { 
  v.hide(); 
});
felixsigl
  • 2,900
  • 1
  • 23
  • 16
0

You can have multiple selectors in jQuery separated with comma:

$("#foo, #bar").hide();
jorgebg
  • 6,560
  • 1
  • 22
  • 31
  • Of course, but I want to combine instantiated objects, something like `$.($foo, $bar).hide()` – aL3xa Mar 23 '11 at 14:04
0

If you're doing this for many id's, maybe do something like:

items = ['foo', 'bar'];
cache = {};
$.each(items, function(i,key) {
    cache[key] = $('#' + key);
    cache[key].hide();
});

Then later on access the 'cache' like cache['foo'].

0

Define a class for all these elements and then hide by the class

$('#foo').addClass('toHide'); 
//Later
$('.toHide').filter(':visible').hide();
WorldIsRound
  • 1,544
  • 10
  • 15
  • Class selectors are way slower than id selectors. I can always define a class, but it's a no-no IMHO. – aL3xa Mar 23 '11 at 14:10