我想要:

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

其他回答

对于那些使用Angular的:

angular.isElement

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

这里有一个使用jQuery的技巧

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

$(obj).html() == undefined // true
$(element).html() == undefined // false

把它放到一个函数里

function isElement(obj){

   return (typeOf obj === 'object' && !($(obj).html() == undefined));

}

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

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

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

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

使用这里发现的根检测,我们可以确定例如alert是否是对象根的成员,那么它很可能是一个窗口:

function isInAnyDOM(o) { 
  return (o !== null) && !!(o.ownerDocument && (o.ownerDocument.defaultView || o.ownerDocument.parentWindow).alert); // true|false
}

要确定对象是否是当前窗口甚至更简单:

function isInCurrentDOM(o) { 
  return (o !== null) && !!o.ownerDocument && (window === (o.ownerDocument.defaultView || o.ownerDocument.parentWindow)); // true|false
}

这似乎比开头线程中的try/catch解决方案更便宜。

没有P

检测元素是否属于HTML DOM的最简单的跨浏览器方法如下所示:

function inHTMLDom(myelement){
    if(myelement.ownerDocument.documentElement.tagName.toLowerCase()=="html"){
        return true;
    }else{
        return false;
    }
}

inHTMLDom(<your element>); // <your element>:element you are interested in checking.

在IE6,IE7,IE8,IE9,IE10,FF,Chrome,Safari,Opera中测试。