我想要:

document.createElement('div')  //=> true
{tagName: 'foobar something'}  //=> false

在我自己的脚本中,我曾经只使用这个,因为我从来不需要tagName作为属性:

if (!object.tagName) throw ...;

所以对于第二个目标,我想出了下面的快速解决方案——这基本上是有效的。;)

问题是,它依赖于浏览器强制执行只读属性,而并非所有浏览器都这样做。

function isDOM(obj) {
  var tag = obj.tagName;
  try {
    obj.tagName = '';  // Read-only for DOM, should throw exception
    obj.tagName = tag; // Restore for normal objects
    return false;
  } catch (e) {
    return true;
  }
}

有好的替代品吗?


当前回答

您可以尝试将它附加到一个真正的DOM节点…

function isDom(obj)
{
    var elm = document.createElement('div');
    try
    {
        elm.appendChild(obj);
    }
    catch (e)
    {
        return false;
    }

    return true;
}

其他回答

区分一个原始js对象和一个HTMLElement

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

使用:

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

/ /或

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

在Firefox中,您可以使用Node实例。该节点在DOM1中定义。

但在IE中就没那么容易了。

"instanceof ActiveXObject"只能说明它是一个本机对象。 “typeof document.body。appendChild=='object'"说明它可以是DOM对象,也可以是其他具有相同功能的对象。

如果有任何异常,只能使用DOM函数和catch来确保它是DOM元素。然而,它可能有副作用(例如改变对象内部状态/性能/内存泄漏)

根据mdn

Element是Document中所有对象都继承的最通用基类。它只有对所有类型的元素通用的方法和属性。

我们可以通过原型实现isElement。以下是我的建议:

/** * @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

我有一个特殊的方法来做到这一点,在答案中还没有提到。

我的解决方案基于四个测试。如果对象通过了这四个,那么它就是一个元素:

该对象不是空的。 对象有一个叫做“appendChild”的方法。 方法“appendChild”继承自Node类,而不仅仅是一个冒名方法(具有相同名称的用户创建的属性)。 对象类型为Node Type 1 (Element)。从Node类继承方法的对象总是Node,但不一定是element。

问:如何检查给定的属性是否是继承的,而不是冒名顶替的?

答:要判断一个方法是否真正继承自Node,一个简单的测试是首先验证该属性是否具有“对象”或“函数”类型。接下来,将属性转换为字符串,并检查结果是否包含文本“[Native Code]”。如果结果看起来像这样:

function appendChild(){
[Native Code]
}

然后从Node对象继承了该方法。参见https://davidwalsh.name/detect-native-function

最后,把所有的测试放在一起,解决方案是:

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;
}

每个DOMElement。构造函数返回函数HTML…元素)所以…

function isDOM(getElem){
    if(getElem===null||typeof getElem==="undefined") return false;
    var c = getElem.constructor.toString();
    var html = c.search("HTML")!==-1;
    var element = c.search("Element")!==-1;
    return html&&element;
}