Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use :contains(text) with any text with jQuery

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 ?

like image 873
Nicolas Viennot Avatar asked Apr 30 '11 16:04

Nicolas Viennot


People also ask

How use contains in 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 do I search for a specific word in a string in 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 you check if a string contains a value in jQuery?

The jQuery :contains() Selector is used to check whether a string contains a substring in jQuery.

How do I select a span containing a specific text value using 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.


1 Answers

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.

like image 198
Lightness Races in Orbit Avatar answered Oct 11 '22 22:10

Lightness Races in Orbit