18

I want to bind multiple elements that are defined as a variable. I know this is possible:

$('selector1, selector2').bind(...)

But I want to do something like this:

$($element1, $element2, $element3).bind(...)

Any ideas?

1
  • Probably not the best, but just for fun, you could do $($element1.selector + ", " + $element2.selector + ", " + $element3.selector) Commented Jul 6, 2013 at 1:29

2 Answers 2

24

You have to add them to one result set:

$element1.add($element2).add($element3).bind(...)

Or for an arbitrary number of elements:

var elems = [$element1, $element2, $element3, ...];
var $result = $();

$.each(elems, function() {
    $result = $result.add(this);
});

$result.bind(...);

Or with Array.reduce:

[$element1, $element2, $element3, ...].reduce(function($result, $elem) {
    return $result.add($elem);
}, $()).bind(...);
Sign up to request clarification or add additional context in comments.

Comments

4

You can use add();

var $all = $element1.add($element2).add($element3).bind( ... ); //.add(...)

4 Comments

I assumed (probably wrongly) that the elements where js objects, I updated my answer just in case
Test it. jQuery wraps array objects differently than it wraps DOM objects.
It won't work with jQuery instances, I know, I should have mention that. I hope the edit ammends that
The first one was considering non jquery objects. But you're right, and it's confusing, so I'll edit the answer and I'll leave the last part. But just to clarify, your fiddle it's missing the 0 in the get methods, that's why it didn't work jsfiddle.net/Uj9hk/3

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.