Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching an event to multiple elements at one go

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...?

like image 722
Andreas Grech Avatar asked Sep 07 '09 07:09

Andreas Grech


People also ask

How do you add an event listener to multiple elements with the same class?

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.

Can multiple listeners be attached to an event?

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").


1 Answers

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) 
like image 103
Gareth Avatar answered Sep 21 '22 18:09

Gareth