jQuery: Bind Multiple Different Elements to a Function CodeUnit 09 AUG 2010

The question for today is how to bind a single function to multiple different elements (in other words, elements with either different classes or IDs) in a single call.

Well actually, this is remarkably simple, but only because I JUST discovered that since day 1, jQuery supports the concept of a multiple selector!

Simply put, you can specify as many selectors as you want to in the standard format, though you are delimiting them with a comma, and jQuery will then combine the results returned by the multiple selections into a single result set.

(Note: another way to achieve this multiple selection is by using the combinator .add() method)

An example of this in the wild could be:

$('#message-ajax,.error-notice,.success-notice').click(function(){
  $(this).hide();
});

Nifty. You learn something new every day! :)

Related Link: http://api.jquery.com/multiple-selector/

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.