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

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

    I have a special way to do this that has not yet been mentioned in the answers.

    My solution is based on four tests. If the object passes all four, then it is an element:

    1. The object is not null.

    2. The object has a method called "appendChild".

    3. The method "appendChild" was inherited from the Node class, and isn't just an imposter method (a user-created property with an identical name).

    4. The object is of Node Type 1 (Element). Objects that inherit methods from the Node class are always Nodes, but not necessarily Elements.

    Q: How do I check if a given property is inherited and isn't just an imposter?

    A: A simple test to see if a method was truly inherited from Node is to first verify that the property has a type of "object" or "function". Next, convert the property to a string and check if the result contains the text "[Native Code]". If the result looks something like this:

    function appendChild(){
    [Native Code]
    }
    

    Then the method has been inherited from the Node object. See https://davidwalsh.name/detect-native-function

    And finally, bringing all the tests together, the solution is:

    function ObjectIsElement(obj) {
        var IsElem = true;
        if (obj == null) {
            IsElem = false;
        } else if (typeof(obj.appendChild) != "object" && typeof(obj.appendChild) != "function") {
            //IE8 and below returns "object" when getting the type of a function, IE9+ returns "function"
            IsElem = false;
        } else if ((obj.appendChild + '').replace(/[\r\n\t\b\f\v\xC2\xA0\x00-\x1F\x7F-\x9F ]/ig, '').search(/\{\[NativeCode]}$/i) == -1) {
            IsElem = false;
        } else if (obj.nodeType != 1) {
            IsElem = false;
        }
        return IsElem;
    }
    
    0 讨论(0)
  • 2020-11-22 16:25

    You can see if the object or node in question returns a string type.

    typeof (array).innerHTML === "string" => false
    typeof (object).innerHTML === "string" => false
    typeof (number).innerHTML === "string" => false
    typeof (text).innerHTML === "string" => false
    
    //any DOM element will test as true
    typeof (HTML object).innerHTML === "string" => true
    typeof (document.createElement('anything')).innerHTML === "string" => true
    
    0 讨论(0)
  • 2020-11-22 16:25

    For the ones using Angular:

    angular.isElement
    

    https://docs.angularjs.org/api/ng/function/angular.isElement

    0 讨论(0)
  • 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"
                }
              }
            }
          }
        }
      }),
    )
    <div id=test></div>
    <blockquote id="ok"></blockquote>
    <p id=p></p>
    <br id=o>
    <!--think of anything else you want--!>

    0 讨论(0)
  • 2020-11-22 16:27

    The following IE8 compatible, super-simple code works perfectly.

    The accepted answer does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML well as SVG.

    See it in action here: https://jsfiddle.net/eLuhbu6r/

    function isElement(element) {
        return element instanceof Element || element instanceof HTMLDocument;  
    }
    
    0 讨论(0)
  • 2020-11-22 16:27

    here's a trick using jQuery

    var obj = {};
    var element = document.getElementById('myId'); // or simply $("#myId")
    
    $(obj).html() == undefined // true
    $(element).html() == undefined // false
    

    so putting it in a function:

    function isElement(obj){
    
       return (typeOf obj === 'object' && !($(obj).html() == undefined));
    
    }
    
    0 讨论(0)
提交回复
热议问题