What's the best way to detect if a given Javascript object is a DOM Element? [duplicate]

情到浓时终转凉″ 提交于 2019-12-04 00:26:33

jQuery checks the nodeType property. So you would have:

var overloaded = function (arg) {
    if (arg.nodeType) {
        // Code for DOM Element argument...
    }
};

Although this would detect all DOM objects, not just elements. If you want elements alone, that would be:

var overloaded = function (arg) {
    if (arg.nodeType && arg.nodeType == 1) {
        // Code for DOM Element argument...
    }
};

Probably this one here:

node instanceof HTMLElement

That should work in most browsers. Otherwise you have to duck-type it (eg. typeof x.nodeType != 'undefined')

What about

obj instanceof HTMLElement
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!