1

I am checking for string inside of a div element using jquery but it allways returns the if never the else even when the dom doesn't contain then $ what stupid mistake am i making?

$('.bw-switcher').on('click', function() {
    $(this).toggleClass('toggledrate', 1000);
    $('.toggledrate > .bwswitch-button:before').toggle('fast');
    $('.toggle_rates').toggle('fast');
    if ($(".deatils.dailyPrice:contains($)")) {
        $('.deatils.dailyPrice').toggle('fast');
        console.log('I am the if');
    } else {
        console.log('I am the else');
        $('.deatils.dailyPrice').toggle('fast').prepend('$');
    }
    $('.toggledrate > .bwswitch-button:after').toggle('fast');
});
Esailija
  • 138,174
  • 23
  • 272
  • 326
vimes1984
  • 1,684
  • 3
  • 26
  • 59

2 Answers2

9

Because $(".deatils.dailyPrice:contains($)") is an object and not null objects are always evaluated as true in if tests.

From the MDN :

Any value that is not undefined, null, 0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement

You probably want

if ($(".deatils.dailyPrice:contains($)").length) {
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

The jQuery function constructs a jQuery object. Objects are always considered true in a truthiness evaluation such as if.

Try this

if( $(".deatils.dailyPrice:contains($)").length > 0 )
Esailija
  • 138,174
  • 23
  • 272
  • 326