jQuery select based on text

前端 未结 1 1843
暗喜
暗喜 2020-11-27 22:15

I need to select an element based on its text in jQuery.

For instance:

this text

I know I can use .contain

相关标签:
1条回答
  • 2020-11-27 22:58

    You have some leverage with the :contains selector, but that only goes so far. You will need to further trim down the set of elements based on exact text matches, as in:

    $("span:contains(this text)")
    .filter
    (
      function()
      {
        return $(this).text() === "this text";
      }
    )
    

    This makes the initial contains usage technically unnecessary, but you may experience performance benefits by starting out with a smaller collection of SPAN elements before filtering down to the exact set you're interested in.

    EDIT: Took Ken Browning's suggestion to use the text() function instead of innerHTML for string comparison within the filter function. The idea being that innerHTML will capture text that we're not particularly interested in (including markup).

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