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.
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.
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 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.
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”).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With