Detect DOM object vs. jQuery Object

后端 未结 6 1450
忘掉有多难
忘掉有多难 2021-01-31 08:55

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 i

相关标签:
6条回答
  • 2021-01-31 09:28

    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
    }
    
    0 讨论(0)
  • 2021-01-31 09:30

    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.

    0 讨论(0)
  • 2021-01-31 09:34

    The classy way:

    function is_jquery_object(x) {
        return window.jQuery && x instanceof jQuery;
    }
    
    function is_dom_object(x) {
        return window.HTMLElement && x instanceof HTMLElement;
    }
    

    Building on @karim79's answer, if you need to be sure it's either a DOM or jQuery object, use these tests. (The window test helps the function fail gracefully if the class is not defined, e.g. jQuery failed to load.)

    0 讨论(0)
  • 2021-01-31 09:35

    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.

    0 讨论(0)
  • 2021-01-31 09:43

    jQuery does it like this:

    if ( selector.nodeType )
    

    (jQuery 1.4.3, line 109)

    0 讨论(0)
  • 2021-01-31 09:49

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

    if(elm instanceof jQuery) {
        ...
    }
    

    or:

    if(elm instanceof $) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题