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?
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.
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.
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.
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%.
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'));
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