Domanda

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?

È stato utile?

Soluzione

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");

Altri suggerimenti

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.

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')");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top