Skip to content Skip to sidebar Skip to footer

Detect Dom Object Vs. Jquery Object

I have a function that I want to be able to allow passing in either a regular javascript DOM element object or a jQuery object. If its not yet a jQuery object I will then make it o

Solution 1:

To test for a DOM element, you can check its nodeType property:

if( elm.nodeType ) {
    // Was a DOM node
}

or you could check the jQuery property:

if( elm.jquery ) {
    // Was a jQuery object
}

Solution 2:

To test for a jQuery object, you can use the instanceof operator:

if(elm instanceof jQuery) {
    ...
}

or:

if(elm instanceof $) {
    ...
}

Solution 3:

jQuery does it like this:

if ( selector.nodeType )

(jQuery 1.4.3, line 109)

Solution 4:

The easiest way is to simply pass it into the jQuery function either way. If it's already a jQuery object, it will return it unchanged:

function(elem){
   elem = $(elem);
   ...
}

From the jQuery source code, this is what's happening:

if (selector.selector !== undefined) {
    this.selector = selector.selector;
    this.context = selector.context;
}

return jQuery.makeArray( selector, this );

Where makeArray is merging the new (default) jQuery object with the passed in one.

Solution 5:

elm instanceof jQuery is the most foolproof way, as testing elm.nodeType would mistake {nodeType:1} for a DOM element, and testing elm.jquery would mistake {jquery:$()} for a jQuery object, in addition to there being no guarantee future jQuery objects won't have a jquery property.

Post a Comment for "Detect Dom Object Vs. Jquery Object"