Using jQuery, I want to select a link that contains exactly some kind of text. For example:
<p><a>This One</a></p>
<p><a>"This One?"</a></p>
<p><a>Unlikely</a></p>
I have tried this:
$('a:contains("This One")')
But it picks the first AND the second link. I just want the first link, which contains exactly "This One". How can I do that?
How to get the selected value from a drop-dwon:
console.log($("option").textEquals("Option One"));
- it will return the value of the drop-downA coworker of mine extended jQuery with a function to do this:
The result is that you can select something by exact text this way:
This makes it easy, since you don't have to remember the exact syntax each time. His entire post is here: jQuery Custom Selector for selecting elements by exact text :textEquals
So Narnian's answer works pretty well. Using it in the wild, however, I ran into some issues, where things that I would have expected to get found were not getting found. This was because sometimes there is random white space surrounding the element's text. It is my belief that if you're searching for "Hello World", you would still want it to match " Hello World ", or even "Hello World \n". Thus, I just added the "trim()" method to the function, which removes surrounding whitespace, and it started to work better. Also, I modified the variable names to be a little clearer to my mind.
Specifically...
And secondary note... trim only removes whitespace before and after the searched text. It does not remove whitespace in the middle of the words. I believe this is desirable behavior, but you could change that if you wanted.