我想要:

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

有好的替代品吗?


当前回答

测试变量是否是DOM元素的简单方法(冗长,但更传统的语法:-)

function isDomEntity(entity) {
  if(typeof entity  === 'object' && entity.nodeType !== undefined){
     return true;
  }
  else{
     return false;
  }
}

或者像HTMLGuy建议的那样(简洁的语法):

const isDomEntity = entity =>
  typeof entity === 'object' && entity.nodeType !== undefined

其他回答

这里有一个使用jQuery的技巧

var obj = {};
var element = document.getElementById('myId'); // or simply $("#myId")

$(obj).html() == undefined // true
$(element).html() == undefined // false

把它放到一个函数里

function isElement(obj){

   return (typeOf obj === 'object' && !($(obj).html() == undefined));

}

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

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

    return true;
}

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

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

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

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

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

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