If you don't know the class of the desired object and just want to go after the link text it is possible to use
$(".myClass:contains('My Text')")
If you even don't know which element it is (e.g. a, p, link, ...) you can use
$(":contains('My Text')")
(just leaving the part before :
blank.)
I have to add here that it brings up all elements beginning from <html>
-Tag down to the desired element. A solution I could provide is adding .last()
to it, but this one only works if there's only a single element to find. Maybe sbdy. knows a better solution here.
Actually, this should be an addition to the accepted answer, especially to @Amalgovinus question.
You could create a custom selector similar to :contains
for exact matches:
$.expr[':'].containsexactly = function(obj, index, meta, stack)
{
return $(obj).text() === meta[3];
};
var myAs = $("a.myclass:containsexactly('My Text')");
$("a.myclass:contains('My Text')")
First, select all tags containing 'MY text'. Then for each exact match, if it matches the condition do what ever you want to do.
$(document).ready(function () {
$("a:contains('My Text')").each(function () {
$store = $(this).text();
if ($store == 'My Text') {
//do Anything.....
}
});
});
If you are only bothered if the anchor's text contains a particular string, go with @Dave Morton's solution. If, however, you want to exactly match a particular string, I would suggest something like this:
$.fn.textEquals = function(txt) {
return $(this).text() == txt;
}
$(document).ready(function() {
console.log($("a").textEquals("Hello"));
console.log($("a").textEquals("Hefllo"))
});
<a href="blah">Hello</a>
Slightly improved version (with a second trim parameter):
$.fn.textEquals = function(txt,trim) {
var text = (trim) ? $.trim($(this).text()) : $(this).text();
return text == txt;
}
$(document).ready(function() {
console.log($("a.myclass").textEquals("Hello")); // true
console.log($("a.anotherClass").textEquals("Foo", true)); // true
console.log($("a.anotherClass").textEquals("Foo")); // false
});
<a class="myclass" href="blah">Hello</a>
<a class="anotherClass" href="blah"> Foo</a>
I think this should work for the exact match thing..
$("a.myclass").html() == "your text"