31

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?

1

3 Answers 3

53

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I wanted to avoid repeating the selector string, but of course it can go into a variable if that's the most efficient way.
I might have been unclear : Using $("#id1,#id2") isn't the most efficient way. I just wanted to point that you shouldn't worry for performances here, but you should use what makes your code readable and simple.
Thanks again. Just discovered the selector property, so now it's $(jqId1.selector+','+jqId2.selector). :)
jqId1.add(jqId2) would be faster (which isn't important) and in my opinion clearer than $(jqId1.selector+','+jqId2.selector).
10

You can use each cycle:

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

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

Comments

0

I know this sound a little stupid, but you can also try like this.

$([
    jqId1.get(0),
    jqId2.get(0),
    jqId3.get(0),
    ... // more jQuery elements
]).show();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.