Detect DOM object vs. jQuery Object

后端 未结 6 1461
忘掉有多难
忘掉有多难 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: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.)

提交回复
热议问题