652

Is there a fast way of checking if an object is a jQuery object or a native JavaScript object?

example:

var o = {};
var e = $('#element');

function doStuff(o) {
    if (o.selector) {
        console.log('object is jQuery');
    }
}

doStuff(o);
doStuff(e);

obviously, the code above works but it's not safe. You could potentially add a selector key to the o object and get the same result. Is there a better way of making sure that the object actually is a jQuery object?

Something in line with (typeof obj == 'jquery')

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • 3
    As of jQuery 3.0 this is definitely not a correct way to check for an object being a jQuery object because the `selector` property was deprecated long ago and removed in 3.0. Even in earlier versions, a jQuery object can have an empty selector string, for example `$(window)` has no selector. Use `instanceof` instead. – Dave Methvin Jul 18 '16 at 15:43

9 Answers9

939

You can use the instanceof operator:

if (obj instanceof jQuery){
    console.log('object is jQuery');
}

Explanation: the jQuery function (aka $) is implemented as a constructor function. Constructor functions are to be called with the new prefix.

When you call $(foo), internally jQuery translates this to new jQuery(foo)1. JavaScript proceeds to initialize this inside the constructor function to point to a new instance of jQuery, setting it's properties to those found on jQuery.prototype (aka jQuery.fn). Thus, you get a new object where instanceof jQuery is true.


1It's actually new jQuery.prototype.init(foo): the constructor logic has been offloaded to another constructor function called init, but the concept is the same.

Joe DF
  • 5,438
  • 6
  • 41
  • 63
Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • 9
    So do you mean `if (obj instanceof jQuery){...}`? –  Oct 25 '13 at 14:48
  • 2
    @NigelAngel: Yup, that's what he means :) – ChaseMoskal Oct 28 '13 at 07:45
  • 12
    This doesn't work in case of multiple jQuery instances on a page. – Georgii Ivankin Jan 10 '14 at 12:51
  • @Georgiy Ivankin: you're telling me multiple jquery script includes on a page break the `instanceof` JavaScript operator? Or did you fail to capture the essense of the answer: that `instanceof jQuery1` , `instanceof jQuery2`, etc work to answer the OPs question? – Crescent Fresh Apr 09 '14 at 20:24
  • 5
    @CrescentFresh I mean if I have $ in my current namespace pointing to jQuery2 and I have an object from outer namespace (where $ is jQuery1) than I have no way to use instanceof for checking if this object is a jQuery object. – Georgii Ivankin Apr 11 '14 at 04:00
  • 8
    If you're not sure whether jQuery is loaded at the time of the if statement, you can extend the check to be `typeof jQuery === 'function' && obj instanceof jQuery` since `jQuery` does not have to be declared in order for the `typeof` operator to work without throwing an error. – Patrick Roberts Aug 17 '15 at 19:05
  • 2
    Certainly an edge case here but doing `$(342)` returns a JQuery object, and has length ([342]), but technically is not a valid JQuery object as the API will not work on it. (e.g. $(342).height()) – Hanna Feb 01 '16 at 18:17
  • This does not work in an npm package that does not declare `jquery` as a dependency. – Karl.S Dec 15 '17 at 05:22
  • 2
    Checking for an element NOT being jQuery is `if(!(obj instanceof jQuery))`. The double parentheses are needed, not sure why. Leaving out the inner parentheses (like this: `if(!obj instanceof jQuery)`) returns `false` every time. – Skeets Jul 26 '19 at 09:46
116

You may also use the .jquery property as described here: http://api.jquery.com/jquery-2/

var a = { what: "A regular JS object" },
b = $('body');

if ( a.jquery ) { // falsy, since it's undefined
    alert(' a is a jQuery object! ');    
}

if ( b.jquery ) { // truthy, since it's a string
    alert(' b is a jQuery object! ');
}
mt81
  • 3,288
  • 1
  • 26
  • 35
  • 13
    As [David](http://stackoverflow.com/users/210578/david) pointed out in the question, checking a property of a variable who's value could be null (i.e. if "a" or "b" were null) is not safe (it will throw a TypeError). Using "b instanceof jQuery" is better. – rstackhouse Sep 26 '12 at 14:33
  • 27
    This way works if jQuery is not loaded, whereas `b instanceof jQuery` throws a ReferenceError if jQuery isn’t available on the page. Both approaches are useful in different cases. – Nate Jan 05 '13 at 00:44
  • More efficient maybe, but still not safe. It may require `try ... catch`, particularly in oldIE. – ClarkeyBoy Mar 23 '13 at 21:14
  • In cases where it's possible that jQuery is not loaded, you can use `if ((typeof jQuery !== 'undefined') && (obj instanceof jQuery)) {...` – Harry Pehkonen Sep 23 '15 at 13:42
  • That's not such a good example.. more likely `a` would be a DOM node, like `document.body` and then, theoretically there is a chance the `jquery` key somehow came to be ontop of that node's chain. – vsync Jul 13 '17 at 13:26
  • Let's say you want to write a function that accepts both Element and jQuery objects to be passed. `instanceof` requires your library to take a dependency to jQuery while checking the `jquery` property doesn't. I prefer to check `jquery` and treat the object like any array-like type if it exists. This way you don't force the clients of your library to have jQuery as a dependency while allowing the ones that do to pass their jQuery objects and expect your function work. – Şafak Gür Feb 06 '18 at 12:32
32

Check out the instanceof operator.

var isJqueryObject = obj instanceof jQuery
Corey Sunwold
  • 10,194
  • 6
  • 51
  • 55
26

The best way to check the instance of an object is through instanceof operator or with the method isPrototypeOf() which inspects if the prototype of an object is in another object's prototype chain.

obj instanceof jQuery;
jQuery.prototype.isPrototypeOf(obj);

But sometimes it might fail in the case of multiple jQuery instances on a document. As @Georgiy Ivankin mentioned:

if I have $ in my current namespace pointing to jQuery2 and I have an object from outer namespace (where $ is jQuery1) then I have no way to use instanceof for checking if that object is a jQuery object

One way to overcome that problem is by aliasing the jQuery object in a closure or IIFE

//aliases jQuery as $
(function($, undefined) {
    /*... your code */

    console.log(obj instanceof $);
    console.log($.prototype.isPrototypeOf(obj));

    /*... your code */
}(jQuery1));
//imports jQuery1

Other way to overcome that problem is by inquiring the jquery property in obj

'jquery' in obj

However, if you try to perform that checking with primitive values, it will throw an error, so you can modify the previous checking by ensuring obj to be an Object

'jquery' in Object(obj)

Although the previous way is not the safest (you can create the 'jquery' property in an object), we can improve the validation by working with both approaches:

if (obj instanceof jQuery || 'jquery' in Object(obj)) { }

The problem here is that any object can define a property jquery as own, so a better approach would be to ask in the prototype, and ensure that the object is not null or undefined

if (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery)) { }

Due to coercion, the if statement will make short circuit by evaluating the && operator when obj is any of the falsy values (null, undefined, false, 0, ""), and then proceeds to perform the other validations.

Finally we can write an utility function:

function isjQuery(obj) {
  return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));
}

Let's take a look at: Logical Operators and truthy / falsy

jherax
  • 5,238
  • 5
  • 38
  • 50
  • How does that improve safety, though? Non-jQuery objects with a jquery property would still be misdetected. I don't see what else using both approaches might "improve", either. – Gui Prá Jan 31 '15 at 11:50
  • this is a easy way to check whether an object is a jQuery object, if for any reason you suspect that someone is creating objects with properties such as _jquery_, then you can create a validator more robust, i.e. checking for properties in the _prototype:_ ***myObj.constructor.prototype.jquery*** or better yet, you can use the function ***[Object.prototype.isPrototypeOf()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/IsPrototypeOf)*** – jherax Feb 01 '15 at 13:42
  • 1
    If you `||` any of that with a `'jquery' in Object(obj)`, though, it goes to drain, because it won't prevent non-jQuery objects with that property from passing the verification. I do believe checking for that property in the prototype improves the situation, though. Maybe you should add that to your answer! I don't think any other answer here mentions that possibility :) – Gui Prá Feb 02 '15 at 00:50
  • 1
    isn't `obj.__proto__.jquery` instead of `obj.constructor.prototype.jquery` enough? just a bit short :) – Axel Jul 03 '17 at 09:35
  • 1
    @Axel yes, it works too :). I used `constructor.prototype` because `obj` is supposed to be an instance of the constructor, that is `jQuery`. On the other hand `__proto__` is available for any kind of object. – jherax Jul 04 '17 at 20:00
5

For those who want to know if an object is a jQuery object without having jQuery installed, the following snippet should do the work :

function isJQuery(obj) {
  // All jQuery objects have an attribute that contains the jQuery version.
  return typeof obj === "object" && obj != null && obj.jquery != null;
}
Karl.S
  • 2,294
  • 1
  • 26
  • 33
  • The `&& obj &&` is to check if obj is not `null`, because `typeof null` returns 'object' too. It could be `obj !== null`, but this is correct too. – Nuno Rafael Figueiredo Jun 14 '22 at 18:40
  • @NunoRafaelFigueiredo Updated my seven years old answer, taking your remark in consideration, and improving comparison with `obj != null` which is better since it also excludes `undefined`. – Karl.S Jun 15 '22 at 01:24
4

However, There is one more way to check the object in jQuery.

jQuery.type(a); //this returns type of variable.

I have made example to understand things, jsfiddle link

Shaunak Shukla
  • 2,347
  • 2
  • 18
  • 29
3
return el instanceof jQuery ? el.size() > 0 : (el && el.tagName);
j0k
  • 22,600
  • 28
  • 79
  • 90
johnchou
  • 31
  • 1
  • To check for a DOM element, better use `nodeType` property, and to ensure a `boolean` value be returned, you can use double negation `!!(el && el.nodeType)` – jherax Jul 28 '14 at 22:26
2

You can check if the object is produced by JQuery with the jquery property:

myObject.jquery // 3.3.1

=> return the number of the JQuery version if the object produced by JQuery. => otherwise, it returns undefined

-9
var elArray = [];
var elObjeto = {};

elArray.constructor == Array //TRUE
elArray.constructor == Object//TALSE

elObjeto.constructor == Array//FALSE
elObjeto.constructor == Object//TRUE