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

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

    Not to hammer on this or anything but for ES5-compliant browsers why not just:

    function isDOM(e) {
      return (/HTML(?:.*)Element/).test(Object.prototype.toString.call(e).slice(8, -1));
    }
    

    Won't work on TextNodes and not sure about Shadow DOM or DocumentFragments etc. but will work on almost all HTML tag elements.

提交回复
热议问题