How to find elements that match multiple conditions
Asked Answered
R

3

17

What I need to do is find all a elements on the page that contain "tag" in the href property and the text of the element contains certain word.

For example

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

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

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

I can also find all a elements with 'cars' in the text like this:

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

But how do I combine these 2 conditions into a single statement that says: Find all a elements that contain 'tag' in the href and contain 'cars' in the text?

Rabblerousing answered 6/3, 2013 at 23:34 Comment(0)
W
25

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

You can go on and on forever that way, i.e.

$("a.className.anotherClass[href*=tag][title=test]:contains('cars'):visible");
Whomp answered 6/3, 2013 at 23:36 Comment(0)
J
5

As the other guys said or, if the two conditions need to be applied separately, with some other code in between for example, then ...

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

then later ...

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

.filter() is the generalized method for reducing an existing jQuery selection.

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

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

.filter() is also good for reasons I wasn't about to explain, and I don't need to because @bažmegakapa has just done so very eloquently.

Jadejaded answered 6/3, 2013 at 23:43 Comment(1)
Another nice feature I did now know about.Rabblerousing
P
4

The other answers show fine and working examples. But there is an interesting quirk here, the distinction between native CSS selectors (that are also supported by the native querySelectorAll()) and selectors defined by jQuery.

Mixing them might not be fortunate, because then the much quicker native engine cannot be used. For example on :has() the jQuery docs state:

Because :has() is a jQuery extension and not part of the CSS specification, queries using :has() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.

For this reason, you might better off querying with the native method and then filtering by using any jQuery specific selectors:

var $res = $("a[href*=tag]").filter(":contains('cars')");
Profusive answered 6/3, 2013 at 23:47 Comment(1)
+1 Nice explanation. Should be on every jQuery newbie's reading list.Jadejaded

© 2022 - 2024 — McMap. All rights reserved.