Given multiple anchor tags:
<a class="myclass" href="...">My Text</a>
How do I select the anchors matching the class and with some specific text. eg Select all anchors with the class:'myclass' and text:'My Text'
Given multiple anchor tags:
<a class="myclass" href="...">My Text</a>
How do I select the anchors matching the class and with some specific text. eg Select all anchors with the class:'myclass' and text:'My Text'
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>
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')");