0

I know I can use $.each to apply the same event handler to two different jQuery objects. I'm surprised it was not possible to have a cleaner syntax such as:

  var $span = $('span');
  var $div = $('div');

  var clickHandler = function () {
    $(this).toggleClass('red');
  }

  $($span, $div).on('click', clickHandler); // <-- Neater syntax
  $([$span, $div]).on('click', clickHandler); // <-- A little worse, but still better than $.each

Why do the syntaxes I have tried not work? Is there a neater alternative to using $.each?

3 Answers 3

2
$span.add($div).on('click', clickHandler)

Should do what you want, per the add() docs.

  1. $($span, $div) is being interpreted as $span's which are descendants of $div.
  2. $([$span, $div]) expects the array elements to be DOMElements, not jQuery objects (I've always wished this was possible as well)

You can see both of these syntaxs described in the jQuery documentation

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

Comments

2

You can use CSS syntax for multiple selectors - the comma ,:

$('span, div').on('click', clickHandler);

Or if you have variables containing the elements, you can use add()

$span.add($div).on('click', clickHandler);

Comments

1

You can also use jQuery's .add()link method to extend a wrapped set

$span.add( $div ).on( 'click', clickHandler );

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.