How to use 2 classes for the same function with jQuery

How to execute the same function for two classes?

I have it:

$('.buythis').click(function(){ blabla } 

And I want to use the same line for another class, for example:

  $('.anotherclass').click(function(){ blabla } 

Now ... how can I use the same click function without reuse? I want something like:

  ($('.buythis'),$('.anotherclass')).click(function(){ blabla } 
+4
source share
4 answers

Try the following:

  $('.buythis, .anotherclass').click(function(){ blabla } 
+9
source

Use a comma between two selectors:

 $('.buythis, .anotherclass').click( ... ); 

or use two selectors encoded with .add() .

 $('.buythis').add('.anotherclass').click( ... ); 

The latter syntax can be useful if the selector is complex, as it can eliminate the ambiguity from the parser and make the code more readable.

+4
source

Then use the following code:

 $('.buythis, .anotherclass').click(function(){ blabla } 
+1
source

Using multiple selector 1 :

 $('.buythis, .anotherclass').click(function(){ blabla }); 
+1
source

All Articles