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

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

    The using the root detection found here, we can determine whether e.g. alert is a member of the object's root, which is then likely to be a window:

    function isInAnyDOM(o) { 
      return (o !== null) && !!(o.ownerDocument && (o.ownerDocument.defaultView || o.ownerDocument.parentWindow).alert); // true|false
    }
    

    To determine whether the object is the current window is even simpler:

    function isInCurrentDOM(o) { 
      return (o !== null) && !!o.ownerDocument && (window === (o.ownerDocument.defaultView || o.ownerDocument.parentWindow)); // true|false
    }
    

    This seems to be less expensive than the try/catch solution in the opening thread.

    Don P

提交回复
热议问题