Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ] */
like image 795
pyon Avatar asked Feb 25 '11 16:02

pyon


People also ask

What is $( this in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

What does jQuery selector return?

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).


1 Answers

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

like image 179
BoltClock Avatar answered Nov 15 '22 04:11

BoltClock