检测给定的JavaScript对象是否是DOM元素的最佳方式是什么? [英] What's the best way to detect if a given Javascript object is a DOM Element?

查看:101
本文介绍了检测给定的JavaScript对象是否是DOM元素的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我正在编写一个旨在接受多个参数类型的函数:

  var overloaded = function(arg ){
if(is_dom_element(arg)){
// DOM元素参数的代码...
}
};

实现 is_dom_element 的最佳方式是什么? -browser,相当准确的方式?

解决方案

jQuery检查nodeType属性。所以你会有:

  var overloaded = function(arg){
if(arg.nodeType){
// DOM元素参数的代码
}
};

尽管这样可以检测所有的DOM对象,而不仅仅是元素。如果你想要单独的元素,那将是:

  var overloaded = function(arg){
if(arg。 nodeType&& arg.nodeType == 1){
//代码DOM元素参数...
}
};


Say for instance I was writing a function that was designed to accept multiple argument types:

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

What's the best way to implement is_dom_element so that it works in a cross-browser, fairly accurate way?

解决方案

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

这篇关于检测给定的JavaScript对象是否是DOM元素的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆