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

后端 未结 30 2706
-上瘾入骨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:25

    The only way to guarentee you're checking an actual HTMLEement, and not just an object with the same properties as an HTML Element, is to determine if it inherits from Node, since its impossible to make a new Node() in JavaScript. (unless the native Node function is overwritten, but then you're out of luck). So:

    function isHTML(obj) {
        return obj instanceof Node;
    }
    
    console.log(
      isHTML(test),
      isHTML(ok),
      isHTML(p),
      isHTML(o),
      isHTML({
        constructor: {
          name: "HTML"
        }
      }),
      isHTML({
        __proto__: {
          __proto__: {
            __proto__: {
              __proto__: {
                constructor: {
                  constructor: { 
                    name: "Function"
                    
                  },
                  name: "Node"
                }
              }
            }
          }
        }
      }),
    )


提交回复
热议问题