Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does contains selector only work with .length?

Tags:

jquery

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?

like image 242
LazyPeon Avatar asked Mar 16 '26 12:03

LazyPeon


1 Answers

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.)

like image 90
Ariel Avatar answered Mar 18 '26 02:03

Ariel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!