Select link by text (exact match)

2019-01-08 10:25发布

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?

10条回答
叛逆
2楼-- · 2019-01-08 11:02
var link = $('a').filter(function(index) { return $(this).text() === "Availability"; });
 $(link).hide();
        $(link).removeAttr('href');
查看更多
孤傲高冷的网名
3楼-- · 2019-01-08 11:05

How to get the selected value from a drop-dwon:

$.fn.textEquals = function (text) {
    var match = false; 
    var values="";
    $(this).each(function () {
        if ($(this).text().match("^" + text + "$")) {
            values=$(this).val();
            match = true;
            return false;
        }
    });
    return values;
};

console.log($("option").textEquals("Option One")); - it will return the value of the drop-down

查看更多
趁早两清
4楼-- · 2019-01-08 11:07

A coworker of mine extended jQuery with a function to do this:

$.expr[':'].textEquals = function(a, i, m) {
    return $(a).text().match("^" + m[3] + "$");
};

The result is that you can select something by exact text this way:

$("label:textEquals('Exact Text to Match')");

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

查看更多
放荡不羁爱自由
5楼-- · 2019-01-08 11:07

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...

$.expr[':'].textEquals = function(el, i, m) {
    var searchText = m[3];
    var match = $(el).text().trim().match("^" + searchText + "$")
    return match && match.length > 0;
}

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.

查看更多
登录 后发表回答