2

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++){}
    }
};

5 Answers 5

8

jQuery objects have a property called 'jquery':

>>> $('body').jquery
"1.5.2"
Sign up to request clarification or add additional context in comments.

Comments

1

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(...
}

Comments

1

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

Comments

0

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.