user3861559 user3861559 - 1 month ago 13
jQuery Question

Multiple variables in jquery selector

I have a code like this

$(".class1 .class2").on('click', function(){
//Do something
});


I am trying to somehting like this using variables:

var1=".class1";
var2=".class2"

$(var1 var2).on('click', function(){
//Do something
});


I see
var1
and
var2
are set to right values, but everytime I try to use 2 variables as selector it fails. When I keep the click trigger unchanged and use
var1
or
var2
elsewhere in the code individually (just
var1
or
var2
but not in the same selector list) it works. Any tips?

I figure I use
var3
concatenate
var1
and
var2
, but I am trying to reduce another variable.

Answer

You're missing the space, without it, it becomes .class1.class2 which means the element has to have both classes, not get the descendant of the first one etc.

var1 = ".class1";
var2 = ".class2";

$(var1 + ' ' + var2).on('click', function(){
   //Do something        
});

Another option would be find()

$(var1).find(var2).on(...

Just doing $(var1 var2) would be the same as var fail = var1 var2; it's a syntax error.

Comments