24

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.

1 Answer 1

34

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

Sign up to request clarification or add additional context in comments.

3 Comments

Good answer, but why use innerHTML instead of $(this).text()? Wouldn't using innerHTML require him to account for cases where the criteria includes characters which have to be encoded (like & -> &amp;)
For nitpicking, I gave you +1 and a referral in the answer!
@DavidAndres Instead of innerHTML you could also use innerText which is faster than .text() and would not include markup.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.