Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery OR Selector?

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?

like image 540
Suan Avatar asked Feb 15 '10 03:02

Suan


People also ask

What is jQuery used for?

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

Is jQuery the same as JavaScript?

The main difference among the three is that JavaScript is client-side, i.e., in the browser scripting language, whereas jQuery is a library (or framework) built with JavaScript.

Which is better js or jQuery?

Though JavaScript is the basic language from which jQuery has evolved, jQuery makes event handling, DOM manipulation, Ajax calls much easier than JavaScript. jQuery also allows us to add animated effects on our web page which takes a lot of pain and lines of code with JavaScript.

Is jQuery still used?

jQuery is one of the longest-running and most influential JavaScript libraries on the web. A staggering 78% of the top 1 million websites use jQuery in some way, according to BuiltWith. As for the most talked-about JavaScript library today, React, it's used by a relatively paltry 14%.


2 Answers

Use a comma.

'.classA, .classB' 

You may choose to omit the space.

like image 89
Daniel A. White Avatar answered Sep 17 '22 19:09

Daniel A. White


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')); 
like image 37
Alp Avatar answered Sep 20 '22 19:09

Alp