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

Using jQuery you can use:

$(":contains(hello)")

It will return any matching element containing 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 to find elements containing "hello :)" using jQuery?

+5
source share
4 answers

See this answer for how to do this.

It basically includes .filterto get around a known bug:contains :

$('#demo').filter(function(i, el) {
    return !!$(el).text().match(/hello :\)/);
});

Live example .

, .length 1, , .

+4

jQuery:

( ! "# $% & '() * +,./:; <= > ? @[] ^` {|} ~) , :\\

$(":contains('hello \\:\\)')")
0

:

jQuery.fn.contains = function(re) {
  return this.filter(function(i, el) {
    return !$(el).text().match(RegExp(re));
  });
};

:

$("*").contains(":\\)") // returns all elements in the page that contains ':)'

Note. contains () accepts a regex (this means you need to avoid what you need to escape for regex)

0
source

All Articles