Reputation: 878
Is something like this possible? I have multiple variables set to DOM elements. Instead of hitting the DOM again to get set the event handlers, I want to use the variables I already have set.
var a = $("#foo");
var b = $("#bar");
a,b.on("click", function() {
});
Upvotes: 1
Views: 1522
Reputation: 780782
You can use an array as the argument to $()
and it will create a new collection of everything in it. It doesn't hit the DOM again.
$([a, b]).on("click", function() {
...
});
However, it requires that the array contain DOM elements, not jQuery objects. You can turn a jQuery collection into an array of the elements with .get()
. Since you'll get nested arrays, you can then use .flat()
to flatten this. For ID selectors this isn't really needed, since you could just select the first element with .get(0)
, but the method below generalizes to collections of multiple elements.
var a = $('#foo');
var b = $('#bar');
$([a.get(), b.get()].flat()).on("click", function() {
alert('Does this work?');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="foo"> Foo </button>
<button id="bar"> Bar </button>
Upvotes: 1
Reputation: 3730
You can use .add()
to chain the cached elements.
var a = $("#foo");
var b = $("#bar");
(a).add(b).on("click", function() {
alert('Handler registered');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="foo">Foo</button>
<button id="bar">Bar</button>
When you are dealing with multiple cached elements, a more elegant solution would be, as Barmar suggests, to pass them as an array to $()
.
However, take care to pass in only the first item of the cached jQuery object so that you are actually targeting the DOM element itself, not the jQuery wrapper object.
var a = $("#foo");
var b = $("#bar");
var c = $("#biz");
$([a[0], b[0], c[0]]).on("click", function() {
alert('Handler registered');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="foo">Foo</button>
<button id="bar">Bar</button>
<button id="biz">Biz</button>
Upvotes: 3
Reputation: 187
In JQuery you can use the same notation as in CSS to afect multiple elements, just separate them using a comma.
$('#foo, #bar').on("click", function () {})
Upvotes: 0