Mark
Mark

Reputation: 33671

jquery writing an if

I have some code like this:

if ($(event.target).is('.class1') || $(event.target).is('.blab') || $(event.target).is('.foo') || $(event.target).is('.cbncvbn') || $(event.target).is('.dfghdfgh') || $(event.target).is('.tryrty')) {
    // Do something
}

Is there a more succinct way to write this?

PS: I know there are better ways to do the same thing, but this question is about the syntax of the conditions.

Thanks.

Upvotes: 2

Views: 141

Answers (2)

bobince
bobince

Reputation: 536775

In theory hasClass would be the most appropriate way to test whether an element has a given class name. However jQuery itself implements hasClass like this:

this.is( "." + selector )

which is not only just the same code in the end, but also breaks badly if you have a class name containing punctuation with a meaning in selectors. Bad jQuery, no cake!

So I'd stick with Paolo's answer. If performance is an issue the speed could be improved by using plain JavaScript to split the className list just once. But probably it won't matter in this case.

Upvotes: 2

John Leidegren
John Leidegren

Reputation: 61077

Well, jQuery uses CSS3 selectors you can just as well do this:

if ($(event.target).is('.class1, .blab, .foo, .cbncvbn, .dfghdfgh, .tryrty')) {
    // Do something
}

The match applies to any, as it does with CSS rules

Upvotes: 4

Related Questions