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?
1. $$ has no significance to jQuery; its use is an arbitrary decision by whomever authored whatever it is your looking at.
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.
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.
Yes, you can separate the selectors with a comma:
if($el.is(".classA, .classB"))
See it in action.
You can test if
if($el.is('.classA, .classB')) { ... }
Here is a little test case: http://jsfiddle.net/ydtv2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With