Skip to content Skip to sidebar Skip to footer

How Do I Store Multiple Jquery Selectors In A Javascript Variable?

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 sel

Solution 1:

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.

var object1 = $('#object1'),
    object2 = $('#object2');

object1.some_method();

update

In reference to your comment:

jQuery offers the .add() method which allows to concat jQuery objects:

object1.add(object2).method();

Solution 2:

Not completely sure I understand what you mean. You want to store the jQuery objects so you don't have to continually search for them like some sort of cache?

var cache = newObject();
cache['#object1'] = $('#object1');
cache['#object2'] = $('#object2');

To retrieve the jQuery values, you'd merely have to call cache['#object1'].

Solution 3:

You can use .add():

var object1 = $('#object1'), object2 = $('#object2');

object1.add(object2).addClass('couple');

Or,

var multiple = [object1[0], object2[0], ...];

$(multiple).addClass('party');

Solution 4:

a selector is a string when passed to the $() fn. returns a collection of Elements that match the selector. So there is nothing wrong with this code.

Your code can also be written as,

var object1 = "#object1",
    object2 = "#object2";

$(object1).add(object2).doSomething();

or it can be further optimized as,

var object1 = $('#object1'),
    object2 = $('#object2');

object1.add(object2).doSomething();

where doSomething can be a jQuery or jQuery plugin defined method.

Solution 5:

Why don't you use the easy way.

var severalVar = 'h1,h2,h3,h4,h5,h6';
 $(severalVar).hide()

Post a Comment for "How Do I Store Multiple Jquery Selectors In A Javascript Variable?"