How to select all anchor tags with specific text

后端 未结 6 1640
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 20:21

Given multiple anchor tags:

My Text

How do I select the anchors matching the class and wi

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 21:07

    If you are only bothered if the anchor's text contains a particular string, go with @Dave Morton's solution. If, however, you want to exactly match a particular string, I would suggest something like this:

    $.fn.textEquals = function(txt) {
        return $(this).text() == txt;
    }
    
    $(document).ready(function() {
        console.log($("a").textEquals("Hello"));
        console.log($("a").textEquals("Hefllo"))
    });
    
    Hello
    

    Slightly improved version (with a second trim parameter):

    $.fn.textEquals = function(txt,trim) {
        var text = (trim) ? $.trim($(this).text()) : $(this).text();
        return text == txt;
    }
    
    $(document).ready(function() {
        console.log($("a.myclass").textEquals("Hello")); // true
        console.log($("a.anotherClass").textEquals("Foo", true)); // true
        console.log($("a.anotherClass").textEquals("Foo")); // false
    });
    
    Hello
       Foo
    

提交回复
热议问题