1

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() {

});
2

3 Answers 3

3

Solution #1

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>

Solution #2

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>

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

Comments

1

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>

Comments

0

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 () {})

1 Comment

This doesn't answer the question, which was about using variables for the elements.

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.