Darcy
Darcy

Reputation: 5368

How to tell if obj is jquery or plain javascript

This is probably a stupid question but is there a way to tell programmatically if the object is jquery or just plain javascript?

For example:

Utils.Listbox.MoveItemsUp = function(listbox) {

    if(listbox.isJquery()) {
        listbox.each(function(){}); 
    }
    else {
        for(var i = 0; i < listbox.options.length; i++){}
    }
};

Upvotes: 2

Views: 272

Answers (5)

RobertPitt
RobertPitt

Reputation: 57268

What you should remember is that whenever your within a callback the object this is always an native entity and not a jquery object.

for example:

a = $('a').each(function(){
    //'this' is ALWAYS an native object
});

a will always be an instance of jQuery unless your using a specific method that returns a type such as json object, boolean, string etc.

if your recurving variable from a function that's out of your control and you want to know if it's a jQuery object you can do the following:

if(!listbox || !listbox.jquery)
{
     listbox = $(listbox)
}
//the variable is now always going to be a jQuery object.

the reason for this is that jquery always stores an reference to its version within a selected context

Upvotes: 0

Jim Rubenstein
Jim Rubenstein

Reputation: 6930

To test if an object is a jQuery object, you check the jquery attribute of it. so:

<script>
Utils.Listbox.isJquery = function()
{
    return typeof this.jquery != 'undefined';
}
</script>

Upvotes: 0

Chad
Chad

Reputation: 19619

One way is to use jQuerys $.isPlainObject function (doc) That will tell you if it was an object created using {} or new Object, a jQuery object will return false. However, note also that an array, and string and functions will also return false:

var obj = {};
var $obj = $('div');

$.isPlainObject(obj); //returns true
$.isPlainObject($obj); //returns false

Upvotes: 1

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

jQuery is just Javascript. I guess you could test for the existence of a jQuery function though:

if (foo.each)
{
    foo.each(function(...
}
else
{
    $(foo).each(function(...
}

Upvotes: 1

Marco Mariani
Marco Mariani

Reputation: 13776

jQuery objects have a property called 'jquery':

>>> $('body').jquery
"1.5.2"

Upvotes: 8

Related Questions