Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple jquery object variables as selectors?

In jQuery, selecting more than one element can be done like this:

$("#id1,#id2").show(); 

But when I have two jQuery objects, I don't seem to be able to select more than one using the variables themselves. For example:

var jqId1 = $("#id1"); var jqId2 = $("#id2"); $(jqId1).show();       // This works. $(jqId1,jqId2).show(); // This only shows jqId1. 

See jsFiddle: http://jsfiddle.net/jr9Q2/

Is there another way of specifying multiple jq variables as selectors?

like image 781
ingredient_15939 Avatar asked Aug 29 '13 06:08

ingredient_15939


People also ask

Can we use multiple selectors in jQuery?

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.

Can you use a variable in a jQuery selector?

Projects In JavaScript & JQueryYes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.


2 Answers

You can use add :

jqId1.add(jqId2).show(); 

But don't make your code too complex just to avoid querying "#id1,#id2" : this selector relies on getElementById and is very fast.

like image 130
Denys Séguret Avatar answered Sep 20 '22 13:09

Denys Séguret


You can use each cycle:

$([jqId1, jqId2]).each( function(){     $(this).show(); }); 

As answered here: Select multiple jQuery objects with .add()

like image 33
Gytis Vinclovas Avatar answered Sep 20 '22 13:09

Gytis Vinclovas