Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select based on text

Tags:

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.

like image 740
Jourkey Avatar asked Sep 16 '09 00:09

Jourkey


People also ask

How do I select a span containing a specific text value using jQuery?

To select a span containing a specific text value using jQuery, we can select all the spans and then use the filter method to find the one with the given text value. We call $(“span”) to get all the spans. Then we spread the spans into an array with the spread operator.

How do I check if a div contains a text?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

How do I find a word in a string using jQuery?

How to find if a word or a substring is present in the given string. In this case, we will use the includes() method which determines whether a string contains the specified word or a substring. If the word or substring is present in the given string, the includes() method returns true; otherwise, it returns false.

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).


1 Answers

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

like image 150
David Andres Avatar answered Oct 02 '22 06:10

David Andres