Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 376
Andrey Fedorov Avatar asked Jun 27 '10 19:06

Andrey Fedorov


1 Answers

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();
like image 68
Nick Craver Avatar answered Sep 30 '22 12:09

Nick Craver