How do I go about doing this?
$(function() {
var foo = $('#foo'),
bar = $('#bar');
$('body').click(function() {
$(foo,bar).css({color: 'red'});
});
});
Demo: http://jsfiddle.net/each/RGZ4Z/ – Only foo becomes red
Edit: Can i stress the fact that I’m aware I could easily do:
$('#foo,#bar').css({color: 'red'});
I’m simply asking about the usage of variables…
Probably, what you want is this:
Here’s a demo piece of code that shows how this can work: http://jsfiddle.net/jfriend00/3Ep6J/.
There are three choices I can think of depending upon what you want:
var items = $('#foo, #bar')$('#foo, #bar').css({color: 'red'});foo.add(bar).css({color: 'red'});And, more detail on each option:
1) You can either just create one jQuery object in the beginning that has both sets of objects in it like this:
and then later do this:
2) Or just do it all at once:
3) Or, if you already have separate jQuery objects for foo and bar, you can add the items from one jQuery object to the other and then carry out your operation:
and then later, do this:
Note: somewhat counterintuively, option 3) does not modify the
foojQuery object, theaddmethod returns a new jQuery object with the items frombaradded to it.