Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is a jQuery object

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

like image 883
David Hellsing Avatar asked Dec 05 '09 19:12

David Hellsing


People also ask

How do you check if an object is a jQuery object?

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.

What is object object in jQuery?

Introduction to jQuery object. The jQuery object is a collection of DOM elements and behaves like a special array. Everything in jQuery is an object.

Is object empty jQuery?

jQuery isEmptyObject() methodThe isEmptyObject() method is used to determine whether the passed argument is an empty object or not. It returns a Boolean value. If it finds the passed value is an empty object, it returns true. Otherwise, it returns false.


2 Answers

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.

like image 106
Crescent Fresh Avatar answered Sep 21 '22 15:09

Crescent Fresh


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! '); } 
like image 40
mt81 Avatar answered Sep 21 '22 15:09

mt81