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?
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 assign as many handlers as you want to an event using addEventListener().
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(...);
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