How to select all anchor tags with specific text

后端 未结 6 1618
隐瞒了意图╮
隐瞒了意图╮ 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 20:52

    If you don't know the class of the desired object and just want to go after the link text it is possible to use

    $(".myClass:contains('My Text')")
    

    If you even don't know which element it is (e.g. a, p, link, ...) you can use

    $(":contains('My Text')")
    

    (just leaving the part before : blank.)

    I have to add here that it brings up all elements beginning from <html>-Tag down to the desired element. A solution I could provide is adding .last() to it, but this one only works if there's only a single element to find. Maybe sbdy. knows a better solution here.

    Actually, this should be an addition to the accepted answer, especially to @Amalgovinus question.

    0 讨论(0)
  • 2020-12-12 20:54

    You could create a custom selector similar to :contains for exact matches:

    $.expr[':'].containsexactly = function(obj, index, meta, stack) 
    {  
        return $(obj).text() === meta[3];
    }; 
    
    var myAs = $("a.myclass:containsexactly('My Text')");
    
    0 讨论(0)
  • 2020-12-12 21:02
    $("a.myclass:contains('My Text')")
    
    0 讨论(0)
  • 2020-12-12 21:06

    First, select all tags containing 'MY text'. Then for each exact match, if it matches the condition do what ever you want to do.

    $(document).ready(function () {
        $("a:contains('My Text')").each(function () {
            $store = $(this).text();
    
            if ($store == 'My Text') {
                //do Anything.....
            }
        });
    });
    
    0 讨论(0)
  • 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"))
    });
    
    <a href="blah">Hello</a>
    

    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
    });
    
    <a class="myclass" href="blah">Hello</a>
    <a class="anotherClass" href="blah">   Foo</a>
    
    0 讨论(0)
  • 2020-12-12 21:08

    I think this should work for the exact match thing..

    $("a.myclass").html() == "your text"
    
    0 讨论(0)
提交回复
热议问题