508

Is there any way to execute same code for different elements on the page?

$('.class1').click(function() {
   some_function();
});

$('.class2').click(function() {
   some_function();
});

instead to do something like:

$('.class1').$('.class2').click(function() {
   some_function();
});

Thanks

10 Answers 10

980
$('.class1, .class2').on('click', some_function);

Or:

$('.class1').add('.class2').on('click', some_function);

This also works with existing objects:

const $class1 = $('.class1');
const $class2 = $('.class2');
$class1.add($class2).on('click', some_function);
9
  • 12
    To help developers remember this, even if a bit more extended using more psuedo classes it is the same format as applying a css selector when defining styles May 22, 2013 at 19:44
  • 9
    What if had class2 cached like this var class2=$(".class2")?
    – Vivek S
    Jun 6, 2014 at 5:50
  • 25
    @NeverBackDown .add() works with jquery objects too
    – Eevee
    Jun 6, 2014 at 5:51
  • 3
    Note that this will still attach events to jquery objects that exist, even if one of the selectors returns undefined. Aug 7, 2014 at 14:39
  • 3
    can somebody explain what's the real difference between $('.class1, .class2') and $('.class1').add('.class2')? in what case we should use .add()? Mar 23, 2017 at 2:05
139

I normally use on instead of click. It allow me to add more events listeners to a specific function.

$(document).on("click touchend", ".class1, .class2, .class3", function () {
     //do stuff
});
3
  • 1
    I like this way better. But can you target one element by class and one by ID in the same declaration? For e.g. $(document).on("click touchend", ".class1, #id1, .class3", function () { //do stuff }); Jan 4, 2017 at 6:23
  • 3
    a year later: yes, you can! @GauravOjha Jan 26, 2017 at 8:53
  • 7
    This technique--creating a delegated, rather than direct handler--also offers the unique advantage of handling events triggered by matching elements created after registering the handler. See: api.jquery.com/on Apr 26, 2017 at 0:31
46
$('.class1, .class2').click(some_function);

Make sure you put a space like $('.class1,space here.class2') or else it won't work.

19

Simply use $('.myclass1, .myclass2, .myclass3') for multiple selectors. Also, you dont need lambda functions to bind an existing function to the click event.

1
11

Another alternative, assuming your elements are stored as variables (which is often a good idea if you're accessing them multiple times in a function body):

function disableMinHeight() {
    var $html = $("html");
    var $body = $("body");
    var $slideout = $("#slideout");

    $html.add($body).add($slideout).css("min-height", 0);
};

Takes advantage of jQuery chaining and allows you to use references.

9

If you have or want to keep your elements as variables (jQuery objects), you can also loop over them:

var $class1 = $('.class1');
var $class2 = $('.class2');

$([$class1,$class2]).each(function() {
    $(this).on('click', function(e) {
        some_function();
    });
});
5

We can code like following also, I have used blur event here.

$("#proprice, #proqty").blur(function(){
      var price=$("#proprice").val();
      var qty=$("#proqty").val();
      if(price != '' || qty != '')
      {
          $("#totalprice").val(qty*price);
      }
  });
4

Add a comma separated list of classes like this :

jQuery(document).ready(function($) {

$('.class, .id').click(function() { 

//  Your code

    }

});
1

I have a link to an object containig many input fields, which requires to be handled by the same event. So I simply use find() to get all the inside objects, that need to have the event

var form = $('<form></form>');
// ... apending several input fields

form.find('input').on('change', onInputChange);

In case your objects are one level down the link children() instead find() method can be used.

1

In addition to the excellent examples and answers above, you can also do a "find" for two different elements using their classes. For example:

<div class="parent">
<div class="child1">Hello</div>
<div class="child2">World</div>
</div>

<script>
var x = jQuery('.parent').find('.child1, .child2').text();
console.log(x);
</script>

This should output "HelloWorld".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.