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?
Two different elements have similar chemical properties when they have the same number of valence electrons in their outermost energy level. Elements in the same column of the Periodic Table have similar chemical properties.
You can use the . some method referenced here. The some() method tests whether at least one element in the array passes the test implemented by the provided function. Also, as a user mentions below, it is also interesting to match "exactly one" appearance like mentioned above (and requested by OP).
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
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");
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')");
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