isekaijin
isekaijin

Reputation: 19772

How to programmatically detect if an object is a jQuery object?

How can I programmatically detect if an object is a jQuery object? For example:

// 1. declare some variables
var vars = [1, 'hello', ['bye', 3], $(body), { say: 'hi' }];

// 2. ??? : implement function that tests whether its parameter is a jQuery object
function isjQuery(arg) { /* ??? */ }

// 3. profit
var test = $.map(vars, isjQuery); /* expected [ false, false, false, true, false ] */

Upvotes: 5

Views: 887

Answers (3)

BoltClock
BoltClock

Reputation: 724452

The easiest API-documented way is to test for the .jquery property:

function isjQuery(arg) {
    return !!arg.jquery;
}

However, if you want to be sure it's a jQuery object and not some other object with a fake .jquery property, the other answers suggesting instanceof jQuery and testing the constructor work too.

(The .jquery property is formally a string indicating the jQuery version, but the API example uses it to test whether an object is a jQuery object.)

Upvotes: 9

Fudgie
Fudgie

Reputation: 413

I think you can rely on

if ( vars[i] instanceof jQuery ) {
  // do something with this jQuery object
}

but I also found these methods here:

obj && obj.constructor == jQuery 
obj && obj.jquery 

Upvotes: 4

Justin Niessner
Justin Niessner

Reputation: 245489

There are several ways, but the clearest (in my opinion) would be:

function isjQuery(arg) { return arg instanceof jQuery; }

Upvotes: 4

Related Questions