MJackson
MJackson

Reputation: 41

Test if a DOM element or JSON

Suppose a function accepts one argument that is whether a DOM element or JSON that are wrapped in jQuery object or not, so how to tell one from the other?

Upvotes: 4

Views: 291

Answers (1)

jAndy
jAndy

Reputation: 236022

you're probably looking for something like this:

var get_unknown_element = function(element) {
        var ele     = element,
            type    = Object.prototype.toString.call(ele);

        // string as passed in, we just assume it to be a jQuery (or querySelectorAll) selector string
        if(type === '[object String]') {                
            return (function(e){
               return e.length ? e : null; 
            }($(ele)));
        }
        // an object was passed in, if we have an jquery object & length > 0, just return it
        else if(type === '[object Object]' && ele.jquery && ele.length) {
            return ele;
        }    
        // native DOM object (node) was passed in, just call the jQuery constructor on it & return           
        else if(/^\[object HTML/.test(type)) {
            return $(ele);
        }
        // return null on no match
        else return null;                         
};

Upvotes: 2

Related Questions