Malyo
Malyo

Reputation: 2000

Combining selectors as variables in jQuery

I'm thinking of what is the best way to combine selector, which i use as variables in my jQuery code. I want to use selectors as variable always, but the thing is that sometimes i want to use them in one statement, so i'm thinking what's the most elegant way to do it.

Should i use add ( (x+y).function... )? Or maybe add strings? Or maybe keep jQuery variables as only id with name so i can combine within single jQuery statement ($ that is)

x = $('#selectorOne');
y = $('#selectorTwo');

Upvotes: 0

Views: 1328

Answers (4)

Pranay Rana
Pranay Rana

Reputation: 176906

Multiple Selector (“selector1, selector2, selectorN”)-You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

Example :

$("div,span,p.myClass").css("border","3px solid red");

or

.add() - Add elements to the set of matched elements.

Example :

$("p").add("div").addClass("widget");

Upvotes: 1

Stasik
Stasik

Reputation: 2614

Since x and y are just arrays, one can use jQuery.merge to combine them. HTH

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

If they're declared as variables you can use add():

x.add(y).something();

Upvotes: 4

Joseph
Joseph

Reputation: 119847

You can store them in an array:

var selectors = [
    '#selector1',
    '#selector2',
    ....
];

and when you want to use them all together, do a comma separated join()

var alljoined = selectors.join(','); //join ALL selectors
$(alljoined).doSomethingToAll();     //and do something to all

you can also choose selectively:

var fewjoined = [                  //select a few selectors...
    selectors[1], 
    selectors[3],
    ...
].join(',');                       //..to join
$(fewjoined).doSomethingToAll();   //and do something

Upvotes: 5

Related Questions