fearofawhackplanet
fearofawhackplanet

Reputation: 53446

How to know if you have a jQuery object

Two questions really...

Firstly, which is the better coding style when writing jQuery functions which take object params, should the function take a jQuery object or is it better to pass a standard JavaScript object and have the function itself do the wrapping? I guess I'm just asking if there is a standard here, since it might not always be obvious to someone who wants to call the function.

And secondly, how do you test if an object is a jQuery object? Ideally it would be nice if the function could take either, so...

function(obj) {
    var $obj;
    if (isJQuery(obj)) {
        $obj = obj;
    }
    else {
        $obj = $(obj);
    }
    // ....
}

or do you even need to do this? will $(obj) simply return if the object is already a jQuery object, so you can always attempt to wrap and it doesn't matter?

Upvotes: 2

Views: 356

Answers (2)

Nick Craver
Nick Craver

Reputation: 630607

You can test for the .jquery property (which is on the prototype of jQuery objects), like this:

function(obj) {
  var $obj = obj.jquery ? obj : $(obj);
}

This is what jQuery core does internally as well.


Update: My ticket filed as a result of this question was completed, you can now find the .jquery property in the official API documentation.


Edit: as @T.J. points out in comments this isn't currently in the official API, however it's been around since jQuery 1.0 and I'm pretty sure it isn't going anywhere. All the same based on comment discussions (thanks T.J.), I submitted an enhancement ticket to hopefully get this added to the API documentation, you can track its progress here: http://bugs.jquery.com/ticket/7200

Upvotes: 8

BoltClock
BoltClock

Reputation: 724452

I would think something along these lines:

    if (obj instanceof jQuery) {
        $obj = obj;
    }
    else {
        $obj = $(obj);
    }

will $(obj) simply return if the object is already a jQuery object, so you can always attempt to wrap and it doesn't matter?

Well, it returns a clone of the jQuery object that you pass (see the documentation). This may probably result in unintended behavior.

Upvotes: 4

Related Questions