Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all anchor tags with specific 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'

like image 539
Geoff Appleford Avatar asked Mar 15 '10 12:03

Geoff Appleford


3 Answers

$("a.myclass:contains('My Text')")
like image 118
David Morton Avatar answered Nov 04 '22 22:11

David Morton


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')");
like image 15
Andy E Avatar answered Nov 04 '22 20:11

Andy E


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>
like image 4
karim79 Avatar answered Nov 04 '22 20:11

karim79