27

Is it possible to test whether a jQuery object has a particular method? I've been looking, but so far without success. Thanks!

Jim Miller
  • 3,291
  • 4
  • 39
  • 57

6 Answers6

46

This should work:

if (!!$.prototype.functionName)
user113716
  • 318,772
  • 63
  • 451
  • 440
hunter
  • 62,308
  • 19
  • 113
  • 113
23

Because jQuery methods are prototype into a jQuery object, you can test it from the prototype object.

if( $.isFunction( $.fn.someMethod ) ) {
    // it exists
}

This uses the jQuery.isFunction()[docs] method to see if $.fn.someMethod is indeed a function. (In jQuery jQuery.fn is a reference to the prototype object.)

user113716
  • 318,772
  • 63
  • 451
  • 440
  • 2
    +1. This is the only one that actually checks if it's a calalble function, and not just a member variable... – ircmaxell Feb 24 '11 at 19:11
  • 2
    For others who are perhaps as slow on the uptake as I am: if you are, for example, checking to see if the UI Tabs method exists, use `$.isFunction($.fn.tabs)`. Hey, I needed a concrete example; maybe someone else does, too. – Ryan Burney Jan 17 '13 at 17:17
  • Deprecated in 3.3.0 – JPollock May 21 '18 at 15:30
5

try

if ($.fn.method) {
    $('a').method(...);
}

or

if ($.method) {
    $.method(...);
}
qwertymk
  • 34,200
  • 28
  • 121
  • 184
0
//Simple function that will tell if the function is defined or not
function is_function(func) {
    return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}

//usage

if (is_function("myFunction") {
        alert("myFunction defined");
    } else {
        alert("myFunction not defined");
    }
Muhammad Tahir
  • 2,351
  • 29
  • 25
0

this worked for me

if (typeof myfunctionname === 'function')
Jay Jara
  • 91
  • 4
-1

You should be able to look for undefined

if( typeof jQuery("*").foo === "undefined" ){
  alert("I am not here!");
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 6
    you could optimize a little by not getting every single element when they're not needed :) – Anurag Feb 24 '11 at 18:30