views:

78

answers:

3

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'

+9  A: 
$("a.myclass:contains('My Text')")
David Morton
Thanks David. How do I do an exact match comparison rather than contains. I only want elements that match exactly.
geoff
I'd only add distinction between links and bookmarks: `​$('a.myclass[href]:contains("My Text")')​​​​`
Marko Dumic
@geoff: There's no built-in way to get an exact match. You can either use the .each function to iterate through them all, or you can write your own jQuery selector. Eric Martin has written a good one for exact match. You can find it here: http://www.ericmmartin.com/creating-a-custom-jquery-selector/
David Morton
@David: Just what I needed. Thank you.
geoff
+1  A: 

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>
karim79
+1  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')");
Andy E