jQuery: find element by text

后端 未结 7 2073
攒了一身酷
攒了一身酷 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:20

    In jQuery documentation it says:

    The matching text can appear directly within the selected element, in any of that element's descendants, or a combination

    Therefore it is not enough that you use :contains() selector, you also need to check if the text you search for is the direct content of the element you are targeting for, something like that:

    function findElementByText(text) {
        var jSpot = $("b:contains(" + text + ")")
                    .filter(function() { return $(this).children().length === 0;})
                    .parent();  // because you asked the parent of that element
    
        return jSpot;
    }
    
    0 讨论(0)
提交回复
热议问题