我想要:

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

有好的替代品吗?


当前回答

测试obj是否继承自Node。

if (obj instanceof Node){
    // obj is a DOM Object
}

Node是HTMLElement和Text继承的一个基本接口。

其他回答

旧线程,但这里有一个更新的可能性为ie8和ff3.5用户:

function isHTMLElement(o) {
    return (o.constructor.toString().search(/\object HTML.+Element/) > -1);
}
var IsPlainObject = function ( obj ) { return obj instanceof Object && ! ( obj instanceof Function || obj.toString( ) !== '[object Object]' || obj.constructor.name !== 'Object' ); },
    IsDOMObject = function ( obj ) { return obj instanceof EventTarget; },
    IsDOMElement = function ( obj ) { return obj instanceof Node; },
    IsListObject = function ( obj ) { return obj instanceof Array || obj instanceof NodeList; },

//事实上我更倾向于内联使用这些快捷方式,但有时为设置代码提供这些快捷方式是很好的

根据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

这是来自可爱的JavaScript库MooTools:

if (obj.nodeName){
    switch (obj.nodeType){
    case 1: return 'element';
    case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
    }
}

不是为了强调这一点,而是为了兼容es5的浏览器,为什么不直接:

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

不会工作在文本节点和不确定的影子DOM或DocumentFragments等,但将工作在几乎所有的HTML标签元素。