Jim Miller
Jim Miller

Reputation: 3329

jQuery test for whether an object has a method?

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

Upvotes: 28

Views: 19529

Answers (6)

Jay Jara
Jay Jara

Reputation: 99

this worked for me

if (typeof myfunctionname === 'function')

Upvotes: -1

Muhammad Tahir
Muhammad Tahir

Reputation: 2485

//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");
    }

Upvotes: 0

qwertymk
qwertymk

Reputation: 35344

try

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

or

if ($.method) {
    $.method(...);
}

Upvotes: 4

hunter
hunter

Reputation: 63562

This should work:

if (!!$.prototype.functionName)

Upvotes: 46

user113716
user113716

Reputation: 322622

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

Upvotes: 23

epascarello
epascarello

Reputation: 207557

You should be able to look for undefined

if( typeof jQuery("*").foo === "undefined" ){
  alert("I am not here!");
}

Upvotes: 0

Related Questions