How do you check if a JavaScript Object is a DOM Object?

后端 未结 30 2707
-上瘾入骨i
-上瘾入骨i 2020-11-22 16:06

I\'m trying to get:

document.createElement(\'div\')  //=> true
{tagName: \'foobar something\'}  //=> false

In my own scripts, I used

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 16:37

    This could be helpful: isDOM

    //-----------------------------------
    // Determines if the @obj parameter is a DOM element
    function isDOM (obj) {
        // DOM, Level2
        if ("HTMLElement" in window) {
            return (obj && obj instanceof HTMLElement);
        }
        // Older browsers
        return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeName);
    }
    

    In the code above, we use the double negation operator to get the boolean value of the object passed as argument, this way we ensure that each expression evaluated in the conditional statement be boolean, taking advantage of the Short-Circuit Evaluation, thus the function returns true or false

提交回复
热议问题