我想要:

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

有好的替代品吗?


当前回答

检测元素是否属于HTML DOM的最简单的跨浏览器方法如下所示:

function inHTMLDom(myelement){
    if(myelement.ownerDocument.documentElement.tagName.toLowerCase()=="html"){
        return true;
    }else{
        return false;
    }
}

inHTMLDom(<your element>); // <your element>:element you are interested in checking.

在IE6,IE7,IE8,IE9,IE10,FF,Chrome,Safari,Opera中测试。

其他回答

这可能很有帮助:isDOM

//-----------------------------------
// Determines if the @obj parameter is a DOM element
function isDOM (obj) {
    // DOM, Level2
    if ("HTMLElement" in window) {
        return (obj && obj instanceof HTMLElement);
    }
    // Older browsers
    return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeName);
}

在上面的代码中,我们使用双重否定操作符来获取作为参数传递的对象的布尔值,这样我们就可以确保条件语句中计算的每个表达式都是布尔值,从而利用短路求值,从而函数返回true或false

我使用这个函数:

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

我认为你要做的是彻底检查一些属性,它们总是在一个dom元素中,但它们的组合不太可能在另一个对象中,像这样:

var isDom = function (inp) {
    return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};

确保你检查的是一个实际的HTMLEement,而不是一个与HTML Element具有相同属性的对象,唯一的方法是确定它是否继承自Node,因为它不可能在JavaScript中创建一个新的Node()。(除非原生Node函数被覆盖,否则就不走运了)。所以:

function isHTML(obj) { return obj instanceof Node; } console.log( isHTML(test), isHTML(ok), isHTML(p), isHTML(o), isHTML({ constructor: { name: "HTML" } }), isHTML({ __proto__: { __proto__: { __proto__: { __proto__: { constructor: { constructor: { name: "Function" }, name: "Node" } } } } } }), ) <div id=test></div> <blockquote id="ok"></blockquote> <p id=p></p> <br id=o> <!--think of anything else you want--!>

测试obj是否继承自Node。

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

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