jQuery: Bind Multiple Different Elements to a Function

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/

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , . Bookmark the permalink.
    blog comments powered by Disqus