3

I'm writing a plugin for jQuery and I want to make it so the user can pass data to the plugin in any form. I have the JSON or array problem worked out, but I'm having trouble trying to determine if the data is a jQuery object.

data = $('#list li');
console.debug( $.isPlainObject(data) );   // false
console.debug( $.isArray(data) );         // false
console.debug( data[0].tagName == "LI" ); // true, but see note below

The last method returns true, but there is no guarantee that the user is using an LI tag for their data, so I think I need something like this:

if ( $.isjQueryObject(data) ) { /* do something */ }

Does anyone know a better method?

1

3 Answers 3

9

The jQuery object (or its alias $) is a plain constructor function, all jQuery objects inherit from the jQuery.prototype object (or its alias jQuery.fn).

You can check if an object exists in the prototype chain of other object, by using either the instanceof operator or the isPrototypeOf method, for example:

function isjQueryObject(obj) {
  return obj instanceof jQuery;
}

Or:

function isjQueryObject(obj) {
  return jQuery.fn.isPrototypeOf(obj);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just as an update, using instanceof causes a memory leak in IE (ajaxian.com/archives/working-aroung-the-instanceof-memory-leak)
1

The jQuery object is simply a collection of elements, stored as an array, with additional functions and stuff attached. So essentially you could use the jQuery elements just like you would a regular array.

2 Comments

Hi thanks for the response, yes I know the jQuery object is stored as an array of objects, but I'm trying to find an easy way to differentiate it from others.
Ah okay, I'd recommend trying @CMS's solution then.
1

How about:

var isJq = data instanceof jQuery;

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.