Obviously it’s a good idea to store jQuery selectors in variables if they are used more than once (not a good idea if used only once).
My question is, how do you store multiple selectors, that are used interchangeably, in a variable.
For instance, let’s say I select $('#object1, #object2), then later on I select `$(‘#object1’). How would I create a variable that can be combined with other variables to create multiple selectors.
If I were to write it like this:
var object1 = "#object1";
var object2 = "#object2";
$(object1 + "," + object2);
I would only be referencing the string #object1, and not the actual selector.
So how do I store multiple selectors in variables, so they can be used interchangeably?
The problem is not the
selector string, the problem is the query of the DOM element. “Problem” means, it’s expensive. That is why you should only query an element once and store a reference to it.update
In reference to your comment:
jQuery offers the
.add()help method which allows to concat jQuery objects: