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

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

    All solutions above and below (my solution including) suffer from possibility of being incorrect, especially on IE — it is quite possible to (re)define some objects/methods/properties to mimic a DOM node rendering the test invalid.

    So usually I use the duck-typing-style testing: I test specifically for things I use. For example, if I want to clone a node I test it like this:

    if(typeof node == "object" && "nodeType" in node &&
       node.nodeType === 1 && node.cloneNode){
      // most probably this is a DOM node, we can clone it safely
      clonedNode = node.cloneNode(false);
    }
    

    Basically it is a little sanity check + the direct test for a method (or a property) I am planning to use.

    Incidentally the test above is a good test for DOM nodes on all browsers. But if you want to be on the safe side always check the presence of methods and properties and verify their types.

    EDIT: IE uses ActiveX objects to represent nodes, so their properties do not behave as true JavaScript object, for example:

    console.log(typeof node.cloneNode);              // object
    console.log(node.cloneNode instanceof Function); // false
    

    while it should return "function" and true respectively. The only way to test methods is to see if the are defined.

提交回复
热议问题