6

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

1 Answer 1

14

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.