Say I have the following :
var a = $("#a"); var b = $("#b"); //I want to do something as such as the following : $(a,b).click(function () {/* */}); // <= does not work //instead of attaching the handler to each one separately
Obviously the above does not work because in the $
function, the second argument is the context
, not another element.
So how can I attach the event to both the elements at one go ?
[Update]
peirix posted an interesting snippet in which he combines elements with the &
sign; But something I noticed this :
$(a & b).click(function () { /* */ }); // <= works (event is attached to both) $(a & b).attr("disabled", true); // <= doesn't work (nothing happens)
From what you can see above, apparently, the combination with the &
sign works only when attaching events...?
Adding event listener to multiple elements To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.
You can do how ever you want it to do. They don't have to be together, it depends on the context of the code. Of course, if you can put them together, then you should, as this probably makes the structure of your code more clear (in the sense of "now we are adding all the event handlers").
The jQuery add method is what you want:
Adds more elements, matched by the given expression, to the set of matched elements
var a = $("#a"); var b = $("#b"); var combined = a.add(b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With