我想要:

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

有好的替代品吗?


当前回答

你可能会感兴趣:

function isElement(obj) {
  try {
    //Using W3 DOM2 (works for FF, Opera and Chrome)
    return obj instanceof HTMLElement;
  }
  catch(e){
    //Browsers not supporting W3 DOM2 don't have HTMLElement and
    //an exception is thrown and we end up here. Testing some
    //properties that all elements have (works on IE7)
    return (typeof obj==="object") &&
      (obj.nodeType===1) && (typeof obj.style === "object") &&
      (typeof obj.ownerDocument ==="object");
  }
}

它是DOM的一部分,第2层。

更新2:这是我如何在我自己的库中实现它: (之前的代码在Chrome中不起作用,因为Node和HTMLElement是函数而不是预期的对象。这段代码在FF3, IE7, Chrome 1和Opera 9中进行了测试。

//Returns true if it is a DOM node
function isNode(o){
  return (
    typeof Node === "object" ? o instanceof Node : 
    o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
  );
}

//Returns true if it is a DOM element    
function isElement(o){
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
    o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}

其他回答

Lo-Dash的_.isElement怎么样?

$ npm install lodash.iselement

在代码中:

var isElement = require("lodash.iselement");
isElement(document.body);

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

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

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

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

我使用这个函数:

函数isHTMLDOMElement(obj) { if (Object.prototype.toString.call(obj).slice(-8) === 'Element]') { 如果(Object.prototype.toString.call (obj)。slice(0,12) === '[object HTML') { 返回true; } 返回错误; } 返回错误; }

https://jsfiddle.net/1qazxsw2/wz7e0fvj/9/

这是来自可爱的JavaScript库MooTools:

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