ian
ian

Reputation: 12335

can i have a multi class selector in jquery

Can I do something like the below where I can have multiple classes trigger an event?

$('a.red a.blue a.green').click(function(event) 
{

});

Upvotes: 10

Views: 3321

Answers (3)

Hailwood
Hailwood

Reputation: 92581

$('a.red.blue.green') selects the elements that have all those classes.

$('a.red, a.blue, a.green') selects the elements that have atleast one of those classes.

Upvotes: 0

Valentin Flachsel
Valentin Flachsel

Reputation: 10825

A slightly different approach would be to prefix your classes like a.prefix_red, a.prefix_blue, a.prefix_green and then use a wildcard selector on it like:

$("a[class^=prefix_]")

The advantage is that as long as you prefix all your "trigger" classes, you don't have to edit the jQuery every time you add a new one, not that it would be a major edit anyways, but might come in handy if you decide to minify your script for example.

Upvotes: 3

BalusC
BalusC

Reputation: 1108642

Yes, you can use the comma as separator.

$('a.red, a.blue, a.green').click(function(event) {});

Upvotes: 18

Related Questions