jQuery: find element by text

后端 未结 7 2072
攒了一身酷
攒了一身酷 2020-11-22 03:31

Can anyone tell me if it\'s possible to find an element based on its content rather than by an id or class?

I am attempting to find

相关标签:
7条回答
  • 2020-11-22 04:02

    Rocket's answer doesn't work.

    <div>hhhhhh
    <div>This is a test</div>
    <div>Another Div</div>
    </div>
    

    I simply modified his DEMO here and you can see the root DOM is selected.

    $('div:contains("test"):last').css('background-color', 'red');
    

    add ":last" selector in the code to fix this.

    0 讨论(0)
  • 2020-11-22 04:08

    Yes, use the jQuery contains selector.

    0 讨论(0)
  • 2020-11-22 04:10

    You can use the :contains selector to get elements based on their content.

    Demo here

    $('div:contains("test")').css('background-color', 'red');
    <div>This is a test</div>
    <div>Another Div</div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    0 讨论(0)
  • 2020-11-22 04:13

    Best way in my opinion.

    $.fn.findByContentText = function (text) {
        return $(this).contents().filter(function () {
            return $(this).text().trim() == text.trim();
        });
    };
    
    0 讨论(0)
  • 2020-11-22 04:15

    Fellas, I know this is old but hey I've this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:

    var text = "text";
    
    var search = $( "ul li label" ).filter( function ()
    {
        return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
    }).first(); // Returns the first element that matches the text. You can return the last one with .last()
    

    Hope someone in the near future finds it helpful.

    0 讨论(0)
  • 2020-11-22 04:15

    The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.

    $('div:contains("test"):not(:has(*))').css('background-color', 'red');
    <div>div1
    <div>This is a test, nested in div1</div>
    <div>Nested in div1<div>
    </div>
    <div>div2 test
    <div>This is another test, nested in div2</div>
    <div>Nested in div2</div>
    </div>
    <div>
    div3
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    0 讨论(0)
提交回复
热议问题