Why does the selector work only with .length?

advertisements

Two cases one works other does not and I wonder why? As this is not transparent for me it really makes me wonder.

Hides the myform:

if($("#msg:contains('Registration successful')").length ) {$("#myform").hide();}

Doesn't work as expected (always hides the myform):

if($("#msg:contains('Registration successful')") ) {$("#myform").hide();}

Why is .length required here?


The .length counts how many DOM objects (i.e. HTML tags) were returned.

Without the .length the javascript just checks if anything at all was returned, and the way jQuery works is that a blank result is still a valid jQuery object. (For example you can chain commands on that object.)