Andrey Fedorov
Andrey Fedorov

Reputation: 9669

Can I use jQuery to select a text node by its contents?

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

Upvotes: 6

Views: 149

Answers (1)

Nick Craver
Nick Craver

Reputation: 630339

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();

Upvotes: 14

Related Questions