With jQuery, one can use:
$(":contains(hello)")
It will return any matching element that contains the text "hello".
I want to be able to match any text, especially "hello :)".
$(":contains(hello :))") // Doesn't work
$(":contains('hello :)')") // Doesn't work
$(":contains('hello :\)')") // Doesn't work
How do I find elements that contains "hello :)" with jQuery ?
The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
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.
The jQuery :contains() Selector is used to check whether a string contains a substring in jQuery.
To check if a span 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 span . If it is, the includes() method returns true , otherwise false is returned.
See this answer for how.
It basically involves .filter
to get around a known :contains
bug:
$('#demo').filter(function(i, el) {
return !!$(el).text().match(/hello :\)/);
});
Live example.
Note that performing .length
on the result of this may give you a value greater than 1 even if only one element contains that text, because the element's parents will also match.
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