views:

33

answers:

1

How do I select an <a href="...">foo</a> DOM node, knowing foo?

+9  A: 

You can use .filter(), like this:

$("a").filter(function() {
  return $(this).text() === "foo";
}).doSomething();

There's also the :contains() selector if you don't need an exact match, like this:

$("a:contains('foo')").doSomething();

Instead of an exact match, this works if the text you're looking for is anywhere in the element.


Alternatively, if you wanted to match exactly and do it often, create a selector for that, like this:

$.expr[":"].textEquals = function(obj, index, meta) { 
  return $(obj).text() === meta[3]; 
} 

Then you could use it anytime after, like this:

$("a:textEquals('foo')").doSomething();
Nick Craver