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

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

    differentiate a raw js object from a HTMLElement

    function isDOM (x){
         return /HTML/.test( {}.toString.call(x) );
     }
    

    use:

    isDOM( {a:1} ) // false
    isDOM( document.body ) // true
    

    // OR

    Object.defineProperty(Object.prototype, "is",
        {
            value: function (x) {
                return {}.toString.call(this).indexOf(x) >= 0;
            }
        });
    

    use:

    o={}; o.is("HTML") // false o=document.body; o.is("HTML") // true

提交回复
热议问题