Jquery writing if

I have a 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 concise way to write this?

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

Thank.

+2


source to share


2 answers


Well jQuery uses a CSS3 selector, you can just as well:

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

      



Matching applies to anyone, just like CSS rules

+4


source


In theory, hasClass would be the most appropriate way to check if an element has a given class name. However, jQuery itself implements hasClass

as follows:

this.is( "." + selector )

      



which is not only the same code at the end, but also breaks down a lot if you have a class name containing punctuation marks with meaning in selectors. Bad jQuery, no pie!

So, I would stick with Paolo's answer. If performance is an issue, speed can be improved by using simple JavaScript to split the className list just once. But it probably doesn't matter in this case.

+2


source







All Articles