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

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

    According to mdn

    Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements.

    We can implement isElement by prototype. Here is my advice:

    /**
     * @description detect if obj is an element
     * @param {*} obj
     * @returns {Boolean}
     * @example
     * see below
     */
    function isElement(obj) {
      if (typeof obj !== 'object') {
        return false
      }
      let prototypeStr, prototype
      do {
        prototype = Object.getPrototypeOf(obj)
        // to work in iframe
        prototypeStr = Object.prototype.toString.call(prototype)
        // '[object Document]' is used to detect document
        if (
          prototypeStr === '[object Element]' ||
          prototypeStr === '[object Document]'
        ) {
          return true
        }
        obj = prototype
        // null is the terminal of object
      } while (prototype !== null)
      return false
    }
    console.log(isElement(document)) // true
    console.log(isElement(document.documentElement)) // true
    console.log(isElement(document.body)) // true
    console.log(isElement(document.getElementsByTagName('svg')[0])) // true or false, decided by whether there is svg element
    console.log(isElement(document.getElementsByTagName('svg'))) // false
    console.log(isElement(document.createDocumentFragment())) // false

提交回复
热议问题