Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an "OR" condition in jquery selector strings?

Tags:

jquery

I would like to test an element object to see if it has either "classA" or "classB". For example, a click() event has returned an element in the event's target property. I want to test this element to see if has either of those two classes.

$("#mybutton").click(function($event) {
  var $el = $($event.target);
  if($el.is(".classA") || $el.is(".classB")) {
    // Can I do the above with 1 selector instead of two separate ones?
  }
});

As above, using the is() function, I can check for each class individually, but I'm curious if I can do it with one function call instead of two?

like image 937
ingredient_15939 Avatar asked Sep 03 '12 11:09

ingredient_15939


People also ask

What is $$ in jQuery?

1. $$ has no significance to jQuery; its use is an arbitrary decision by whomever authored whatever it is your looking at.

What do the jQuery selectors in this code select?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.


2 Answers

Yes, you can separate the selectors with a comma:

if($el.is(".classA, .classB"))

See it in action.

like image 135
Jon Avatar answered Sep 27 '22 21:09

Jon


You can test if

if($el.is('.classA, .classB')) { ... }

Here is a little test case: http://jsfiddle.net/ydtv2/

like image 27
Matteo Tassinari Avatar answered Sep 27 '22 20:09

Matteo Tassinari