Jourkey
Jourkey

Reputation: 34966

jQuery select based on text

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.

Upvotes: 24

Views: 7755

Answers (1)

David Andres
David Andres

Reputation: 31781

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).

Upvotes: 34

Related Questions