jQuery OR Selector?

Viewed 252422

I am wondering if there is a way to have "OR" logic in jQuery selectors. For example, I know an element is either a descendant of an element with class classA or classB, and I want to do something like elem.parents('.classA or .classB'). Does jQuery provide such functionality?

6 Answers

Use a comma.

'.classA, .classB'

You may choose to omit the space.

Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.

The .add() method adds the selected elements to the result set:

// classA OR classB
jQuery('.classA').add('.classB');

It's more verbose than '.classA, .classB', but lets you build more complex selectors like the following:

// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));

Finally I've found hack how to do it:

div:not(:not(.classA,.classB)) > span

(selects div with class classA OR classB with direct child span)

Related