How to find items matching multiple conditions

I need to find all the elements on the page that contain the "tag" in the href property, and the element text contains a specific word.

for example

<a href="/my/tag/item2">cars</a> 

I know that I can get all elements with a tag in href, like this:

 $("a[href*=tag]"); 

I can also find all elements with “machines” in the text as follows:

 $("a:contains('cars')"); 

But how to combine these 2 conditions into one operator, which reads: Find all elements containing a "tag" in href and containing "cars" in the text?

+7
source share
3 answers

Have you tried $("a[href*=tag]:contains('cars')"); ?

You can go on and on forever this way, that is

 $("a.className.anotherClass[href*=tag][title=test]:contains('cars'):visible"); 
+15
source

As the other guys said, or, if two conditions need to be applied separately, with a different code, for example, ...

 var $tags = $("a[href*=tag]"); 

and then...

 var $carTags = $tags.filter(":contains('cars')"); 

.filter() is a generic method for reducing existing jQuery selections.

Like many other jQuery methods .filter() returns a jQuery object, so it will be a chain:

 var $foo = $("a[href*=tag]").filter(":contains('cars')").filter(".myClass"); 

.filter() also good for reasons that I was not going to explain, and I do not need, because @ bažmegakapa just did it very eloquently.

+3
source

Other answers provide excellent and working examples. But there is an interesting quirk here, the difference between the built-in CSS selectors (which are also supported by the native querySelectorAll() ) and the selectors defined by jQuery .

Mixing them cannot be successful, because then a much faster proprietary engine cannot be used. For example, in :has() in jQuery docs it says:

Because: has () is a jQuery extension and not part of the CSS specification, queries using: has () cannot take advantage of the performance enhancement provided by the built-in DOM request of SelectorAll () Method.

For this reason, you may need to poll using your own method and then filter using special jQuery selectors:

 var $res = $("a[href*=tag]").filter(":contains('cars')"); 
+3
source

All Articles