我想要:

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

有好的替代品吗?


当前回答

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

其他回答

对于那些使用Angular的:

angular.isElement

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

接受的答案有点复杂,并且没有检测到所有类型的HTML元素。例如,不支持SVG元素。相反,这个答案适用于HTML和SVG等。

在这里查看它的实际操作:https://jsfiddle.net/eLuhbu6r/

function isElement(element) {
    return element instanceof Element || element instanceof HTMLDocument;  
}

锦上添花:上面的代码与IE8兼容。

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

function isHTMLElement(o) {
    return (o.constructor.toString().search(/\object HTML.+Element/) > -1);
}

这是我的版本。它支持来自iframe的元素

/**
 * @param {any} value
 * @param {any} view Optional. If the value is from an iframe, provide the iframe content window here.
 * @returns {boolean}
 */
function isHtmlElement(value, view) {
  if (value instanceof HTMLElement) return true
  if (view && value instanceof view.HTMLElement) return true

  return !!(
    value &&
    typeof value === 'object' &&
    value !== null &&
    value.nodeType === 1 &&
    typeof value.nodeName === 'string'
  )
}

区分一个原始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