我想要:

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

有好的替代品吗?


当前回答

我使用这个函数:

函数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/

其他回答

如果你正在使用jQuery,试试这个

$('<div>').is('*') // true
$({tagName: 'a'}).is('*') // false
$({}).is('*') // false
$([]).is('*') // false
$(0).is('*') // false
$(NaN).is('*') // false

这是我的版本。它支持来自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

您可以尝试将它附加到一个真正的DOM节点…

function isDom(obj)
{
    var elm = document.createElement('div');
    try
    {
        elm.appendChild(obj);
    }
    catch (e)
    {
        return false;
    }

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