Using two variables set as DOM elements to create a new variable targeting both DOM elements

Viewed 25

Another simple question which I think to be impossible, I am very hopeful you will once again prove me wrong!

Start off with two variables, pointing at DOM elements:

myFirstVariable = $('.my-little-radio input[type=radio]');
mySecondVariable = $('.my-little-select select');

We then need to run a check on any actions made on both of these variables, but only once and in the same function. The question is how do we ping both of the variables into a query selector all style variable to check against?

var myMultiVariable = $(myFirstVariable, mySecondVariable);
myMultiVariable.on('change', function() {
    // I am not crazy!
});

As far as I can tell, the above will only work for the myFirstVariable, and not for the other selectors chained.

Specific question: How can I chain two variables set as DOM elements together to attach an event listener in order to only run the function once?

1 Answers

To explain why your attempt didn't work; it's because the $(a, b) syntax is used to find the a selector within b. It's analogous to $(b).find(a);

There's a couple of ways to do what you require.

One would be to use the add() method:

var myMultiVariable = myFirstVariable.add(mySecondVariable);

Alternatively put both the elements in an array and supply that to the jQuery object:

var myMultiVariable = $([myFirstVariable, mySecondVariable]);
Related