views:

133

answers:

4

Hi

How can i find out if an Object is Wrapped by jQuery.

var obj = $('div');

if(obj is a jQuery wrapped object)
{
   then do something
}

I am quite new in the Javascript World.

Thanks in advance.

+9  A: 

Here you go:

var isJQuery = obj instanceof jQuery;  // or obj instanceof $;
karim79
If it helps the OP, $ is simply an alias to the jQuery function. For this reason "obj instanceof $" would also work.
Paolo Bergantino
... and welcome to the club, karim. :)
Paolo Bergantino
cool stuff. i didn't know this.
Arnis L.
A: 

Not a jQuery user, this is untested, etc. but

if (!(obj instanceof Element))
{
  // ...
}

may work, unless jQuery does weird things in its wrapping. Of course this does require you to know that obj can never be a non-jQuery, non-DOM element, but hopefully that's not hard to enforce.

Jeff Walden
A: 

You can test like this:

if(obj instanceof jQuery) {
    // ...
}

However, it's not entirely correct to say that the HTML element is "wrapped" in a jQuery object, rather the jQuery object is a collection of zero or more HTML elements. So, if you really want to be careful you could test first whether it contains any elements at all, as follows:

if(obj instanceof jQuery && obj.size() > 0) {
    var element = obj[0];
    // do something with element
}
Todd Owen
A: 
if (obj.jquery) {
    /* Do something */
}

That's the simplest way. Checking the object's constructor is another option but note that it won't work across global contexts (e.g. between a parent page and a frame).

J-P