JQuery if H1: contains the word do something

I have successfully used the contains() function, but have never used it with if-statement . My code below does not work when it should. I basically say that if H1 contains the word "truth," do something, if not do something else. Currently, it only shows the first bit of code no matter what is in H1 .. it never shows the else part.

 <H1>This h1 contains the word Star</H1> if ($("H1:contains('True')")) { var test= "<div>IT DID CONTAIN THE WORD TRUE!</div>"; $('h1').append(test); } else { var test= "<div>IT DID <b>NOT</b> CONTAIN THE WORD TRUE!</div>"; $('h1').append(test); } 
+4
source share
5 answers

You need to check the length property of the resulting collection:

 if ($("H1:contains('True')").length) { ... 

Since $("H1:contains('True')") will return an object, and objects will always evaluate the truth.

+10
source

$("H1:contains('True')") is a selector. It returns a jQuery object, not a boolean. To verify that the selector has found any objects, check the length property :

 if ($("H1:contains('True')").length) { // stuff... } 
+1
source

try it

 if ($("H1:contains('True')").length > 0) { var test= "<div>IT DID CONTAIN THE WORD TRUE!</div>"; $('h1').append(test); } else { var test= "<div>IT DID <b>NOT</b> CONTAIN THE WORD TRUE!</div>"; $('h1').append(test); } 
0
source

Using contains, it returns a list.

Refer to this solution:

if contains specific text then run jquery

0
source

The problem is that $("H1:contains('True')") always returns true , because it is always an object. What you really want to check is if it contains elements.

 if ($("H1:contains('True')").length) { 

Now it will return the else part.

Note. I find that :contains case sensitive.

0
source

All Articles