jQuery does not have an ‘exists’ method

As developers, we’ve all solved problems only to forget the solution (and the problem) many months (or years) later.  We’re then forced to rediscover the solution to the old challenge.

I recently encountered this phenomenon while attempting to use jQuery and the ‘exists’ method.  I had tons of old Javascript / jQuery code that was using this method.  Consequently, I couldn’t understand why this code wasn’t working in a new project:

if ($('#MyForm').exists()) {
    // Do something
}

This very simple code resulted in error messages in all my web browsers:

Chrome

Uncaught TypeError: Object #<an Object> has no method ‘exists’

Firefox

Error: $(“#MyForm”).exists is not a function

IE 9 BETA:

SCRIPT438: Object doesn’t support this property or method

(nice descriptive error message IE)

Safari

TypeError: Result of expression ‘$(‘#MyForm’).exists’ [undefined] is not a function.

Here is why I was getting this error:

Jquery doesn’t not have an ‘exists’ method.  The only reason this code worked in my old projects is because I had created my own ‘exists’ method.  The code for doing this is extremely simple:

// Create a jQuery exists method
jQuery.fn.exists = function () { return jQuery(this).length > 0; }

As long as this code executes before attempting to use the ‘exists’ method, then everything will work great.  Now I’ve written this blog post and documented this issue.

Future Gabe, you’re welcome!

This entry was posted in Uncategorized. Bookmark the permalink.
  • demitry

    wow dude, good call. Mucho gracias.