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

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

    In Firefox, you can use the instanceof Node. That Node is defined in DOM1.

    But that is not that easy in IE.

    1. "instanceof ActiveXObject" only can tell that it is a native object.
    2. "typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.

    You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)

提交回复
热议问题