How do you check if a JavaScript Object is a DOM Object?

后端 未结 30 2483
-上瘾入骨i
-上瘾入骨i 2020-11-22 16:06

I\'m trying to get:

document.createElement(\'div\')  //=> true
{tagName: \'foobar something\'}  //=> false

In my own scripts, I used

30条回答
  •  有刺的猬
    2020-11-22 16:27

    here's a trick using jQuery

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

    so putting it in a function:

    function isElement(obj){
    
       return (typeOf obj === 'object' && !($(obj).html() == undefined));
    
    }
    

提交回复
热议问题