我想要:
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;
}
}
有好的替代品吗?
使用这里发现的根检测,我们可以确定例如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中测试。