BeNdErR
BeNdErR

Reputation: 17929

Bind event to multiple jquery elements simultaneously

I need to bind the same event (for example click) to n jquery elements. I know I can achieve this result easily with a selector:

$("#first, #second, .third").on("click", function(){});

but what if, instead of a selector, I want to use a list of jquery elements?

This is the solution I'm using right now, assume you get $first and $second as a result of a function:

var $first = $("#first");
var $second = $("#second");

$([$first[0], $second[0]]).on("click", function(){
    alert("click " + this.innerText)
});

find fiddle to play with here: https://jsfiddle.net/0z2r55d6/

as you can see I need to extract, for each jquery element, the HTML element and push it into an array. I find this pretty ugly and unhandy.. Is there a better way to achieve the same result? I didn't find anything in jquery's documentation.

Thanks

Upvotes: 0

Views: 57

Answers (1)

Apul Gupta
Apul Gupta

Reputation: 3034

Using jQuery add() method:

$first.add($second).add($third).on('click', handler);

Upvotes: 1

Related Questions