I need to select an element based on its text in jQuery.
For instance:
<span>this text</span>
I know I can use .contains() to select based on text, but it’s not exclusive.
I don’t want to select:
<span>this text and that text</span>
I want to select the element if it’s the only text of the element.
Aside from using regex, how do I do this with jQuery selectors?
Thanks.
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:
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 ofinnerHTMLfor string comparison within thefilterfunction. The idea being thatinnerHTMLwill capture text that we’re not particularly interested in (including markup).