Is it possible to test whether a jQuery object has a particular method? I've been looking, but so far without success. Thanks!
Asked
Active
Viewed 1.9k times
27
-
2Do you mean `!!$obj.method`? Or is this more complicated than that? – sdleihssirhc Feb 24 '11 at 18:27
-
@sdleihssirhc No need for `!!` in a conditional statement. – alexia Feb 24 '11 at 19:01
-
1@Nyuszika7H My point was just check for truthiness. But it's hard to get that across with just `$obj.method`, so I added the bangs for clarification. – sdleihssirhc Feb 24 '11 at 19:06
-
@sdleihssirhc No problem, there's [not much speed difference](http://jsperf.com/double-bang-in-if). – alexia Feb 24 '11 at 19:08
-
1You have a nice answer [here](http://stackoverflow.com/a/5159690/1257607) – DanielV Jul 15 '15 at 12:12
6 Answers
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
-
2For 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
-
5
try
if ($.fn.method) {
$('a').method(...);
}
or
if ($.method) {
$.method(...);
}

qwertymk
- 34,200
- 28
- 121
- 184
-
1-1, you're calling jQuery unneccessarily in the first example, that's more than 90% slower! http://jsperf.com/jquery-vs-jquery-fn – alexia Feb 24 '11 at 19:00
-
`if ($.method) {` doesn't work for me. I had to use `if ($.fn.method) {` – Kevin Wheeler Mar 21 '16 at 20:42
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
-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
-
6you could optimize a little by not getting every single element when they're not needed :) – Anurag Feb 24 '11 at 18:30