3

I've used the contains()function successfully, but never have used it with an if-statement. My below code doesn't seem to work when it should. I am basically saying if H1 contains the word "true", do something, if not do something else. Currently it only shows the first bit of code no matter what is in the 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);                     
}
Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
ToddN
  • 2,901
  • 14
  • 56
  • 96
  • possible duplicate of [if contains certain text, then run jquery](http://stackoverflow.com/questions/6309870/if-contains-certain-text-then-run-jquery) – Matt Ball Jun 17 '11 at 15:09

5 Answers5

9

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 always evaluate to truthy.

karim79
  • 339,989
  • 67
  • 413
  • 406
1

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

if ($("H1:contains('True')").length) {
    // stuff...
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

try this

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);                     
}
Dave
  • 532
  • 5
  • 8
0

With the contains, it gives back a list.

Refer to this for a solution:

if contains certain text, then run jquery

Community
  • 1
  • 1
dev4life
  • 880
  • 2
  • 8
  • 18
0

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 believe that :contains is case-sensitive.

natedavisolds
  • 4,305
  • 1
  • 20
  • 25