-2

Is it possible, after declaring two vars, to use them together to call a function in jQuery?

like:

var test1 = $('#mytest1');
var test2 = $('#mytest2');

test1,test1.fadeOut(100);
1
  • 1
    I would recommend you to use JSLint to help you to find common mistakes in scripts, If you try to do something like var1, var2.method(), it will say Expected an assignment or function call and instead saw an expression Commented Mar 7, 2019 at 18:25

2 Answers 2

4

Yes. You can just include the selectors within quotes to the $ function:

$('#mytest1, #mytest2').fadeOut(2000);
#mytest1, #mytest2 {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mytest1"></div>
<div id="mytest2"></div>

If you wish to use the existing variables you've already declared, you can use .add() as noted in this answer:

var test1 = $('#mytest1');
var test2 = $('#mytest2');

$(test1).add(test2).fadeOut(2000);
#mytest1, #mytest2 {
  width: 50px;
  height: 50px;
  margin: 5px;
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mytest1"></div>
<div id="mytest2"></div>

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

1 Comment

You should "normally hide" the first snippet and show the second...;) +1
2

If you don't already have two variables, just select both. Ref. http://learn.jquery.com/using-jquery-core/selecting-elements/#selecting-elements-with-a-comma-separated-list-of-selectors

$('#mytest1, #mytest2').fadeOut();

If you already have both in two separate variables, you can combine them. Ref. http://api.jquery.com/add/

test1.add(test2).fadeOut();

2 Comments

Whoops... You actually replied the same as me faster! I did not see. ;)
That's perhaps what I was looking for :) Thanks

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.